OOP2 Lecture Week 02
OOP2 Lecture Week 02
• C# Data Types
• Type Casting
• The keywords readonly and const
• Structures
• Enumeration
• String
• Use of params, ref, out
• Understand the concept of Class and Object
• Learn about constructors
• Variable Types
THE C# BASICS
• Every method signature specifies a type for each input parameter and
for the return value.
TYPES, VARIABLES, AND VALUES
• The .NET Framework class library defines a set of built-in types as well as
more complex types that represent a wide variety of logical constructs,
such as the file system, network connections, collections and arrays of
objects, and dates.
• A typical C# program uses types from the class library as well as user-
defined types that model the concepts that are specific to the program's
problem domain.
TYPES, VARIABLES, AND VALUES
The information stored in a type can include the following:
int a = 5;
int b = a + 2; //OK
bool test = true;
int c = a + test; // Error. Operator '+' cannot be
applied to operands of type 'int'
and 'bool'.
// Declaration only:
float temperature;
string name;
MyClass myClass;
// Declaration with initializers (four examples):
char firstLetter = 'C';
var limit = 3;
int[] source = { 0, 1, 2, 3, 4, 5 };
var query = from item in source where item <= limit select item;
VALUE TYPES
• A data type is a value type if it holds a data value within its own memory space.
• It means variables of these data types directly contain their values.
• For example,
N.B. All the value types derive from System.ValueType, which in-turn, derives from System.Object.
VALUE TYPES
• The value data types are integer-based and floating-point based. C# language
supports both signed and unsigned literals.
• There are 2 types of value data type in C# language.
1) Predefined Data Types - such as Integer, Boolean, Float, etc.
2) User defined Data Types - such as Structure, Enumerations, etc.
N.B. All the value types derive from System.ValueType, which in-turn, derives from System.Object.
DATA TYPES SIZE VALUES
VALUE TYPES sbyte 8 bit -128 to 127
byte 8 bit 0 to 255
short 16 bit -32,768 to 32,767
ushort 16 bit 0 to 65,535
int 32 bit -2,147,483,648 to 2,147,483,647
uint 32 bit 0 to 4,294,967,295
-9,223,372,036,854,775,808 to
long 64 bit
9,223,372,036,854,775,807
ulong 64 bit 0 to 18,446,744,073,709,551,615
char 16 bit 0 to 65535
float 32 bit -1.5 x 1045 to 3.4 x 1038
double 64 bit -5 x 10324 to 1.7 x 10308
decimal 128 bit -1028 to 7.9 x 1028
bool — True or false
REFERENCE TYPES
• Unlike value types, a reference type doesn't store its value directly.
• Instead, it stores the address where the value is being stored.
• In other words, a reference type contains a pointer to another memory
location that holds the data.
REFERENCE TYPES
• The reference data types do not contain the actual data stored in a variable,
but they contain a reference to the variables.
• If the data is changed by one of the variables, the other variable
automatically reflects this change in value.
• There are 2 types of reference data type in C# language.
1) Predefined Types - such as Objects, String.
2) User defined Types - such as Classes, Interface.
THE COMMON TYPE SYSTEM
• It is important to understand two fundamental points about the type system in .NET
1à
• It supports the principle of inheritance. Types can derive from other types, called
base types. The derived type inherits (with some restrictions) the methods,
properties, and other members of the base type.
• The base type can in turn derive from some other type, in which case the derived
type inherits the members of both base types in its inheritance hierarchy.
• All types, including built-in numeric types such as System.Int32 (C# keyword: int),
derive ultimately from a single base type, which is System.Object (C# keyword: object).
• This unified type hierarchy is called the Common Type System (CTS).
THE COMMON TYPE SYSTEM
2à
• Each type in the CTS is defined as either a value type or a reference type.
This includes all custom types in the .NET class library and also your own
user-defined types.
• Reference types and value types have different compile-time rules, and
different run-time behavior.
THE COMMON TYPE SYSTEM
To support multiple programming languages on a single CLR and have the ability to reuse the
FCL, the types of each programming language must be compatible. This binary compatibility
between language types is called the Common Type System (CTS).
Python
CTS
Common Language Specification (CLS)
• For example, C# supports unsigned types, which are non-CLS compliant. For CLS
compliance, you can still use unsigned types within your code so long as you don't
expose them in the public interface of your code, where code written in other
languages can see.
Common Language Specification (CLS)
• Example:
• unsigned int available in C# but not available in VB.NET
int i;
i = "Hello"; // Error: "Cannot implicitly
convert type 'string' to 'int'"
CASTING AND TYPE CONVERSIONS
• However, we might sometimes need to copy a value into a variable or method parameter of
another type.
• For example, we might have an integer variable that you need to pass to a method whose
parameter is typed as double.
• Or we might need to assign a class variable to a variable of an derived type.
• These kinds of operations are called type conversions.
CASTING AND TYPE CONVERSIONS
In C#, we can perform the following kinds of conversions:
• Implicit conversions: No special syntax is required because the conversion is type safe and
no data will be lost. Examples include conversions from smaller to larger integral types, and
conversions from derived classes to base classes.
• Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required
when information might be lost in the conversion, or when the conversion might not succeed
for other reasons. Typical examples include numeric conversion to a type that has less
precision or a smaller range, and conversion of a base-class instance to a derived class.
• For reference types, an implicit conversion always exists from a class to any one of its direct
or indirect base classes. No special syntax is necessary because a derived class always
contains all the members of a base class.
Derived d = new Derived();
Base b = d; // Always OK.
EXPLICIT CONVERSIONS
• However, if a conversion cannot be made
without a risk of losing information, the class Test
{ static void Main()
compiler requires that you perform an explicit {
conversion, which is called a cast. double x = 1234.7;
int a;
• A cast is a way of explicitly informing the // Cast double to int.
compiler that you intend to make the a = (int)x;
conversion and that you are aware that data System.Console.WriteLine(a);
loss might occur. }
}
• To perform a cast, specify the type that you // Output: 1234
are casting to in parentheses in front of the
value or variable to be converted.
EXPLICIT CONVERSIONS
• For reference types, an explicit cast is required if you need to convert from a base type to
a derived type:
• as Operator
• The "as" operator is used to perform conversions between compatible types. Actually, the "as"
operator returns the cast value if the cast can be made successfully.
Class & Object
Mammal
ZooKeeper
feeds - isDead: bool
+ Eat() : void
is a is a
Dog Whale
+ Eat() : void + Eat() : void
Classes
§ Classes can have the following members
§ Constructors/Destructors
§ Fields
§ Methods
§ Indexers
§ Properties
§ Delegates and Events
§ Other types (e.g. structs, enums, interfaces, classes...)
• The drawback of a default constructor is that every instance of the class will
be initialized to the same values and it is not possible to initialize each
instance of the class to different values.
• When a constructor is created as static, it will be invoked only once for all of
instances of the class .
• A static constructor is used to initialize static fields of the class and to write
the code that needs to be executed only once.
Some key points of a static constructor are:
• A static constructor does not take access modifiers or have any parameters.
• A static constructor is called automatically to initialize the class before the
first instance is created or any static members are referenced.
• A static constructor cannot be called directly.
• The user has no control on when the static constructor is executed in the
program.
Members - Initializers
§ Member variables can be initialized by initializer
instead of constructor
§ We can initialize an object without constructor by
specifying public (!) member variables in object
initializer (NOTE: curly braces in this case)
§ this keyword refers to the current instance of
an object
§ this keyword is used:
§ To distinguish parameters from instance members (e.g.
this.hour = hour;)
§ To pass the current object as a parameter
Members - Overloading Methods and
Constructors
§ Overloading – is an ability to have more than
one method with the same name, but with
different signatures (and, optionally, return
type).
§ NOTE: changing only return type does NOT
overload the method.
§ Method signature – is a method name and
parameter list (including parameters’ types)
Destructors
§ Are methods called by the Garbage Collector
thread when the object is to be “finalized”
§ looks like C++ destructors but are completely
different
§ C# destructors are “non-deterministic” i.e.
finalization (removing objects from memory)
cannot be determined when that will happen
§ whereas C++ destructors are invoked in a
“deterministic” manner (see garbage collector)
Destructors
In C#, most of the time, you do not need to code destructors (or finalizers) because
you can trust GC to clean up for you with destructors.
These methods are called implicitly by the C# runtime system's garbage collector.
class TypeName
{
// implicit destructor ~TypeName()
// created for you automatically by C # even if you did not put it in the code
}
set
{
hour = value;
}
}
NOTE: in this example ” hour” is so called “backing field” – private member variable to store the property value
NOTE: To access the property we use “dot” (access) operator on instance.
Members: Automatic Properties
Structs are:
§ lightweight alternative to class
§ CAN implement interfaces
§ Is a value type
§ Implicitly SEALED
§ NO DEFAULT CONSTRUCTOR
§ A struct cannot inherit from another struct or class, and it cannot be the base of a class.
§ Structs, however, inherit from the base class object (System.Object)
Consider: Day3of7/UsingStructs project
§ [attributes] [access-modifiers] struct identifier [: interface-list]
§ {
§ struct-members
§ }
§ When you create a struct object using the new operator, it gets created and the appropriate
constructor is called.
§ (E.g. CoOrds coords2 = new CoOrds(10, 10);)
Structs
• C# 4.0 The Complete Reference; Herbert Schildt; McGraw-Hill Osborne Media; 2010
• Head First C# by Andrew Stellman
• Fundamentals of Computer Programming with CSharp – Nakov v2013
References
C# 4.0 The Complete Reference; Herbert Schildt; McGraw-Hill Osborne Media; 2010