Chapter 3 - The Type System

Embed Size (px)

DESCRIPTION

X

Citation preview

  • The Type System 1C# 30

    C# 3.0C# 3.0

    Chapter 3 The Type System

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Type System IntroductionThe Type System 2C# 30

    Type System Introduction The NET framework defines a type The .NET framework defines a type

    system common to all .NET languages The CTS defines a rich set of types that can be

    hosted by the CLR f E.g., structs, classes, enumerators, interfaces and delegates

    and their basic definition rules Note that in the NET vocabulary we use the term Note that in the .NET vocabulary , we use the term

    type as a general name for any data type: Basic type, structure, class, etc. Basic type, structure, class, etc.

    We use the term instance to refer to an object of a typeyp

    The CTS provides a rich set of basic types

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Type System IntroductionThe Type System 3C# 30

    Type System Introduction Based on this rich and extensive type Based on this rich and extensive type

    system: The .NET Framework defines a set of rules which are

    termed: Common Language Specification (CLS) The CLS can be considered to be the minimum

    specifications that any .NET compliant language must provideprovide

    The C# compiler provides assistance in developing a CLS compliant code This assistance can be obtained using the g[CLSCompliant] attribute

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    NET Basic Data TypesThe Type System 4C# 30

    .NET Basic Data TypesThe CTS pro ides a rich set of pre defined The CTS provides a rich set of pre-defined basic types, for all .NET languages use yp g g This set contains primitive types

    System.Int32, System.Double,, System.DecimalSystem.Int32, System.Double,, System.Decimaland System.String

    Different NET languages define different Different .NET languages define different aliases to these .NET basic types In the next slides you can find the .NET basic types

    with their C# alias data type name and the constant numeric literal if applicable

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • C# NET type mappingThe Type System 5C# 30

    C# .NET type mapping.NET Type Description C# Data Type Literals/ Cast

    System.SByte 8-bit signed integer sbyte Cast

    System.Byte 8-bit unsigned integer byte CastSystem.Int16 16-bit signed integer short Castg g

    System.UInt16 16-bit unsigned integer

    ushort Cast

    System.Int32 32-bit signed integer int Default

    System UInt32 32-bit unsigned uint CastSystem.UInt32 32-bit unsigned integer

    uint Cast

    System.Int64 64-bit signed integer long L,l

    System.UInt64 64-bit unsigned integer

    ulong L,l (if the size exceeds long

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    g gcapacity)

    C# NET type mappingThe Type System 6C# 30

    C# .NET type mapping.NET Type Description C# Data Type Literal/Cast

    System.Single single-precision float F,f(32-bit) floating-point number

    System Double A double-precision double DefaultSystem.Double A double-precision(64-bit) floating-point number

    double Default

    System.Char A Unicode character char 'A', '\x0041', (a 16-bit character) (char)65, '\u0041'

    System.Boolean Boolean value (true or false) bool true, false

    System.Decimal 96-bit decimal value decimal M,m

    System String A string of Unicode string "s" @"\n" "\t"System.String A string of Unicode characters

    string s , @ \n , \t

    System.Object The base class of all types object

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    yp

  • Everything is an objectThe Type System 7C# 30

    Everything is an objectThe base of all NET t pes is The base of all .NET types is System.Object This also includes the .NET primitive types By defining a common base NET allows treating all By defining a common base, .NET allows treating all

    types in common terms Such as: defining collection types to store any type of Such as: defining collection types to store any type of

    elements, defining a generic method that can accept any argument type, etc.

    System.Object contains a set of members that are applicable for any NETmembers that are applicable for any .NET type

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    System ObjectThe Type System 8C# 30

    System.Object

    Some of the S stem Object methods are Some of the System.Object methods are virtual Therefore can be overridden by specific types to

    better represent their characteristicsbetter represent their characteristics ToStringToString()() is a good example

    System.ObjectSystem.Object methods will be presented later in this Syste .ObjectSyste .Object et ods be p ese ted ate t schapter

    The NET CTS System ObjectSystem Object type is mapped The .NET CTS System.ObjectSystem.Object type is mapped in C# to a type called objectobject

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Value Types & Reference TypesThe Type System 9C# 30

    Value Types & Reference Types NET types are divided into two .NET types are divided into two

    categories: Reference Types

    Allocated from the GC heap A reference type variable contains only a reference to the

    actual data, which resides on the heap For example provided the following class:For example, provided the following class:

    classEmployee{{

    publicEmployee(stringname)//privatestringname;

    }}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Reference TypesThe Type System 10C# 30

    Reference Types The statement: The statement:

    Employeee=newEmployee("JoeWise"); Allocates an object space on the heapj p p Assigns it to the required data Returns a reference to this object, to be stored in the reference

    variablevariable

    Being allocated on the heap and indirectly accessed Reference type objects are less efficient in terms of bothReference type objects are less efficient in terms of both

    code size, memory usage and speed The .NET BCL defines lots of reference types

    Generally used types (e.g. String and Array) as well as more specific ones (e.g. IO classes, Networking classes etc.)

    U d fi d fi d f t Users can define user-defined reference types: Classes, interfaces, delegates and events

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Value Types & Reference TypesThe Type System 11C# 30

    Value Types & Reference Types Value Types Value Types

    Value type objects are allocated from the stackA l t i bl t ll t i th d t it lf A value type variable actually contains the data itself

    For example: Th t t t i ti t ii 3232 The statement: intint ii ==3232;;allocates a 32-bit space on the stack and moves a 32-bit value into this space

    Note! It is not the object creation form that determines variable location (stack vs. heap)

    The variable type category (value-type vs. reference-type) determines where the variable will be created

    Value types can be members of some reference type Value types can be members of some reference type In this case they are allocated on the GC heap

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Value TypesThe Type System 12C# 30

    Value TypesBeing directl manip lated Being directly manipulated, Value type objects provide better performance than

    reference type objects Their functionality, however, is limitedy, ,

    Most of the .NET pre-defined primitive t l ttypes are value types The pre-defined DateTime is a value typey

    Enums are also value types

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Value Types vs Reference TypesThe Type System 13C# 30

    Value Types vs. Reference Types Value types and reference types behave Value types and reference types behave

    differently in various situations: When passing them as parameters to a method When passing them as a return value from a method When they are compared When they are assignedy g

    B d thi k l d t k l k t Based on this knowledge, take a look at the code shown in the following slides and gguess what the programs output would be

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Value Types vs. Reference Types The Type System 14C# 30

    Class ExerciseusingSystem;usingSystem;classRefType {

    publicRefType(int k){this.k =k;

    }publicint k;

    }classReferenceValueApp {classReferenceValueApp {

    staticpublicvoidReferenceFunc(RefType obj){obj.k =9;obj. ;

    }staticpublicvoidValueFunc(int i){

    i =42;}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Value Types vs. Reference Types The Type System 15C# 30

    Class ExercisestaticvoidMain(){staticvoidMain(){

    RefType obj1=newRefType(42);int i1=0;Console.WriteLine("ref:{0}val:{1}",obj1.k,i1);ReferenceFunc(obj1);ValueFunc(i1);ValueFunc(i1);Console.WriteLine("ref:{0}val:{1}",obj1.k,i1);

    int i2=i1;i2+=5;Console WriteLine("i1:{0}i2:{1}" i1 i2);Console.WriteLine( i1:{0}i2:{1} ,i1,i2);RefType obj2=obj1;obj2.k+=5;Console.WriteLine("obj1.k:{0}obj2.k:{1}",

    obj1.k,obj2.k);

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Value Types vs. Reference Types The Type System 16C# 30

    Class ExerciseRefType obj3=newRefType(14);RefType obj3=newRefType(14);

    if(obj3==obj1)Console.WriteLine("obj3andobj1AREEQUAL!");

    elseConsole WriteLine("obj3andobj1ARENOTEQUAL!");Console.WriteLine( obj3andobj1ARENOTEQUAL! );

    obj3=obj2;}

    }

    What happened at the second-to-last line? Which object does obj3 reference now? What happened to its previously referenced object?

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Note on Value TypesThe Type System 17C# 30

    Note on Value TypesVal e t pes are deri ed from Value types are derived from System.ValueTypey yp

    Value types are sealed Value types can override objects

    methodsmethods Value types can implement interfaces Value types members initialize to zero Value types hold data, reference types

    hold references and/or value types Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    hold references and/or value types

    Intermediate ThoughtsThe Type System 18C# 30

    Intermediate Thoughts Value types have a simple efficient form Value types have a simple, efficient form,

    in which they can be handled efficiently But all typesall types derive from System.ObjectSystem.Object so they can be treated inSystem.ObjectSystem.Object, so they can be treated in common terms

    This means that a al e t pe ariable can be passed This means that a value type variable can be passed to a method that gets an objectobject as a parameterThis should also mean that the following statements This should also mean that the following statements are valid:

    int i =42;objecto=i;//???

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    objecto i;//???

  • BoxingThe Type System 19C# 30

    BoxingHa ing s ch different forms ho can a Having such different forms, how can a value-type variable be assigned to a yp greference type?

    Lets explore the MSIL code generated from the two Let s explore the MSIL code generated from the two statements above:l l ([0] i t32 i.locals([0]int32i,

    [1]objecto)IL 0000:ldc i4 s42IL_0000:ldc.i4.s42IL_0002:stloc.0IL 0003:ldloc.0_IL_0004:box[mscorlib]System.Int32IL_0009:stloc.1

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    IL_000a:ret

    BoxingThe Type System 20C# 30

    Boxingi t i 42int i =42;object o=i;

    HeapStack

    HeapSystem.Int32

    4242 (i)

    0xdddd (o)

    42

    Note that boxing always creates a new copy of th i i l l t bj tthe original value-type object The two objects, i and o, now exist independently of

    h th

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    each other

  • UnboxingThe Type System 21C# 30

    Unboxing Can we retrieve a boxed value type?Can we retrieve a boxed value type?

    int i =42; locals([0]int32iint i =42;objecto=i;int j=(int)o;//???

    .locals([0]int32i,[1]objecto,[2]int32j)int j (int)o;//??? [ ] j)

    IL_0000:ldc.i4.s42IL_0002:stloc.0IL 0003:ldloc 0IL_0003:ldloc.0IL_0004:box[mscorlib]System.Int32IL_0009:stloc.1_IL_000a:ldloc.1IL_000b: unbox [mscorlib]System.Int32IL 0010:ldind i4IL_0010:ldind.i4IL_0011:stloc.2IL_0012:ret

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    _

    System ObjectSystem Object Class MembersThe Type System 22C# 30

    System.ObjectSystem.Object Class Members Following are the Object class methods Following are the Object class methods,

    that any type in .Net ultimately has:publicvirtualbool Equals(objecto);publicstaticbool Equals(objecto1 objecto2);publicstaticbool Equals(objecto1,objecto2);publicstaticbool ReferenceEquals(objecto1,

    objecto2);publicvirtualint GetHashCode();publicTypeGetType();publicvirtualstringToString();~Object();//(Object.Finalize())protectedobjectMemberwiseClone();

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Comparing Two ObjectsThe Type System 23C# 30

    Comparing Two ObjectsThree eq alit comparing methods Three equality-comparing methods And equality/inequality operators (== and !=) publicvirtualbool Equals(objecto);

    For reference types, compare referencesyp , p For simple value types, bitwise compare This method can (and usually should) be overridden

    publicstaticbool Equals(objecto1,objecto2);objecto1,objecto2);

    Calls o1.Equals(o2)

    publicstaticbool ReferenceEquals( publicstaticbool ReferenceEquals(objecto1,objecto2);

    D t i h th th ifi d bj t f t th

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Determines whether the specified objects refer to the same instance

    Comparing Objects The Type System 24C# 30

    Class Exercise Write next to each output operation Write next to each output operation

    whether the output will be True (T) or F l (F)False (F):usingSystem;

    classCl {}

    classCompareApp{

    staticvoidMain()staticvoidMain(){

    Cl cl1=newCl();Cl cl2 newCl();Cl cl2=newCl();int i =5;int j=5;bj i

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    objecto=i;

  • Comparing Objects The Type System 25C# 30

    Class ExerciseConsole.WriteLine("referenceType:");Console.WriteLine(

    "cl1==cl2:{0}",cl1==cl2); ______Console.WriteLine(

    "cl1.Equals(cl2):{0}",cl1.Equals(cl2)); ______

    Console.WriteLine("Equals(cl1,cl2):{0}",

    l ( l l ))Equals(cl1,cl2)); ______Console.WriteLine(

    "R f E l ( l1 l2) {0}""ReferenceEquals(cl1,cl2):{0}",ReferenceEquals(cl1,cl2)); ______

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Comparing Objects The Type System 26C# 30

    Class ExerciseConsole.WriteLine("ValueType:");Console.WriteLine(

    "i ==j:{0}",i ==j); ______Console.WriteLine(

    "i.Equals(j):{0}",i.Equals(j)); ______Console.WriteLine(

    "Equals(i,j):{0}",Equals(i,j)); ______Console.WriteLine(

    "ReferenceEquals(i,j):{0}",ReferenceEquals(i,j)); ______

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Comparing ObjectsThe Type System 27C# 30

    Class Exercise Console WriteLine("misc:");Console.WriteLine( misc: );Console.WriteLine(

    "ReferenceEquals(cl1,cl1):{0}",ReferenceEquals(cl1,cl1):{0} ,ReferenceEquals(cl1,cl1)); ______

    Console.WriteLine(Co so e. te e("ReferenceEquals(i,j):{0}",ReferenceEquals(i,j)); ______q ( , j)); ______

    Console.WriteLine("ReferenceEquals(i,i):{0}",ReferenceEquals(i,i)); ______

    Console.WriteLine("ReferenceEquals(o,o):{0}",ReferenceEquals(o,o)); ______

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }

    System Object MembersThe Type System 28C# 30

    System.Object Memberspublicvirtualpublicvirtualintint GetHashCodeGetHashCode();(); publicvirtualpublicvirtualintint GetHashCodeGetHashCode();(); Returns a hash code for this object's value A type should override this method if its objects are to

    be used as a key in a hashtable The method should provide a good distribution for its objects

    publicTypepublicTypeGetTypeGetType();();p ypp yp ypyp ();(); Returns a Type-derived object that represents the

    exact runtime type of this objectexact runtime type of this object The returned Type object can be used to retrieve

    type related informationtype related information Will be later discussed in the Reflection context

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • System Object ToString()The Type System 29C# 30

    System.Object.ToString()

    publicvirtualstringToString(); publicvirtualstringToString(); Usually returns the class name Built-in value types return their value, stringstring returns

    the string value

    F d fi d t For user-defined types it is recommended to override this method to return a

    meaningful string representing the objects state Good for debugging purposes too (the debuggerGood for debugging purposes too (the debugger

    displays this in the Watch window and elsewhere)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    System Object MembersThe Type System 30C# 30

    System.Object MembersObject(); ~Object(); publicvirtualstringFinalize(); Though containing a destructor-like method, .NET

    types do not really support destructors in their C++ meaning; will be discussed in the GC chapter

    protectedobjectMemberwiseClone();p j (); Perform a shallow copy on an object

    To implement a deep copy a type should implement To implement a deep copy, a type should implement the ICloneableICloneable interface (Clone()Clone() method)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Type ConversionThe Type System 31C# 30

    Type ConversionThe CTS defines con ersions for basic The CTS defines conversions for basic typesyp It also provides means to define conversions for user-

    defined typesdefined types

    In general, only safe conversions, can be done implicitly Otherwise, conversions must be done explicitly, p y Accepting the possibility of either data loss or

    exception thrownexception thrown

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Converting Basic TypesThe Type System 32C# 30

    Converting Basic Types Integral types: Integral types:

    An implicit conversion exists only when the type to convert to contains any possible value of the type toconvert to contains any possible value of the type to convert from

    An implicit conversion from floatfloat to doubledouble is allowed An implicit conversion from floatfloat to doubledouble is allowed. An implicit conversion from intint, , uintuint, or longlong to floatfloat

    and from longlong to doubledouble is allowed Be aware that precision may be lost

    An implicit conversion from integral type to decimaldecimal type is allowedallowed

    No implicit conversion between decimaldecimal and float/doublefloat/double is allowed

    An implicit conversion from charchar to any type which can hold unsigned short unsigned short is allowed

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • The System Convert ClassThe Type System 33C# 30

    The System.Convert ClassThis class defines many ToXXX static This class defines many ToXXX static methods E.g., ToInt32(string), ToBoolean(int), etc. Letting us convert base data types to other base data Letting us convert base data types to other base data

    types

    I f d t l d i th i In case of data loss during the conversion processp An overflow exception will be thrown

    I f l f i i In case of loss of precision No exception will be thrown

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Converting StringsThe Type System 34C# 30

    Converting StringsReading an integer from the Console Reading an integer from the Console using Convert:g

    ii ii (( ii ())())intint ii =Convert.ToInt=Convert.ToInt3232((Console.ReadLineConsole.ReadLine());());

    Another way is by using the Int32 static Parse function

    intint ii ==int.Parseint.Parse((Console.ReadLineConsole.ReadLine());());

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Chapter SummaryThe Type System 35C# 30

    Chapter Summary CTS is the foundation of the type systemyp y

    The core for the CLR cross-language support NET basic types and their C# aliases .NET basic types and their C# aliases

    In .NET, everything is an objecty g j System.Object is the base of all types

    T di id d i t t t i Types are divided into two categories: Reference types and value typesReference types and value types Boxing and unboxing bridge the gap

    Standard (primitive) conversions are defined by the CTS

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    defined by the CTS