Вы находитесь на странице: 1из 18

The Type System 1

C# 30

C# 3.0
Chapter 3 The Type System

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

The Type System 2

C# 30

Type System Introduction


The .NET
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
E.g., structs, classes, enumerators, interfaces
f
and delegates
and their basic definition rules

Note that in the .NET


NET vocabulary
vocabulary , we use the term
type as a general name for any data type:
Basic type, structure, class, etc.

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


yp
type

The CTS provides a rich set of basic types


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

The Type System 3

C# 30

Type System Introduction


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
provide

The C# compiler provides assistance in


developing a CLS compliant code
This assistance can be obtained using
g the
[CLSCompliant] attribute

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

The Type System 4

C# 30

.NET
NET Basic Data Types
The CTS pro
provides
ides a rich set of pre
pre-defined
defined
yp
for all .NET languages
g g use
basic types,
This set contains primitive types
System.Int32, System.Double,, System.Decimal
and System.String

Different .NET
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

The Type System 5

C# 30

C# .NET
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

Cast

System.Int16

g
integer
g
16-bit signed

short

Cast

System.UInt16

16-bit unsigned
integer

ushort

Cast

System.Int32

32-bit signed integer

int

Default

System UInt32
System.UInt32

32-bit unsigned
integer

uint

Cast

System.Int64

64-bit signed integer

long

L,l

System.UInt64

64-bit unsigned
integer
g

ulong

L,l (if the size


exceeds long
g
capacity)

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

The Type System 6

C# 30

C# .NET
NET type mapping
.NET Type

Description

C# Data Type Literal/Cast

System.Single

single-precision
(32-bit) floating-point number

float

F,f

System Double
System.Double

A double-precision
(64-bit) floating-point number

double

Default

System.Char

A Unicode character
(a 16-bit character)

char

'A', '\x0041',
(char)65, '\u0041'

System.Boolean Boolean value (true or false)

bool

true, false

System.Decimal 96-bit decimal value

decimal

M,m

System String
System.String

A string of Unicode
characters

string

"s"
s ,@
@"\n"
\n , "\t"
\t

System.Object

The base class of all types


yp

object

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

The Type System 7

C# 30

Everything is an object
The base of all .NET
NET ttypes
pes is
System.Object
This also includes the .NET primitive types
By defining a common base
base, .NET
NET allows treating all
types in common terms
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 .NET
NET
type
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 8

C# 30

System Object
System.Object
Some of the System.Object
S stem Object methods are
virtual
Therefore can be overridden by specific types to
better represent their characteristics
ToString
ToString()
() is a good example

Syste
System.Object
.Object methods
et ods will be p
presented
ese ted later
ate in tthis
s
chapter

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

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

The Type System 9

C# 30

Value Types & Reference Types


.NET
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
example, provided the following class:
classEmployee
{
publicEmployee(stringname)//
privatestringname;
}

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

The Type System 10

C# 30

Reference Types
The statement:
Employeee=newEmployee("JoeWise");
Allocates an object
j
space
p
on the heap
p
Assigns it to the required data
Returns a reference to this object, to be stored in the reference
variable

Being allocated on the heap and indirectly accessed


Reference 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.)

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

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

The Type System 11

C# 30

Value Types & Reference Types


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

For example:
Th
The statement:
t t
t int
i t i =
=32
32;
32;
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


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

The Type System 12

C# 30

Value Types
Being directl
directly manip
manipulated,
lated
Value type objects provide better performance than
reference type objects
Their functionality,
y, however,, is limited

Most of the .NET pre-defined primitive


t
types
are value
l types
t
The pre-defined DateTime is a value type
y

Enums are also value types

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

The Type System 13

C# 30

Value Types vs.


vs Reference Types
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
y are assigned
g

B
Based
d on thi
this kknowledge,
l d
ttake
k a llook
k att
the code shown in the following
g slides and
guess what the programs output would be
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 14

C# 30

Value Types vs. Reference Types


Class Exercise
usingSystem;
classRefType {
publicRefType(int k){
this.k =k;
}
publicint k;
}
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

The Type System 15

C# 30

Value Types vs. Reference Types


Class Exercise
staticvoidMain(){
RefType obj1=newRefType(42);
int i1=0;
Console.WriteLine("ref:{0}val:{1}",obj1.k,i1);
ReferenceFunc(obj1);
ValueFunc(i1);
Console.WriteLine("ref:{0}val:{1}",obj1.k,i1);
int i2=i1;
i2+=5;
Console WriteLine("i1:{0}i2:{1}"
Console.WriteLine(
i1:{0}i2:{1} ,i1,i2);
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

The Type System 16

C# 30

Value Types vs. Reference Types


Class Exercise
RefType obj3=newRefType(14);
if(obj3==obj1)
Console.WriteLine("obj3andobj1AREEQUAL!");
else
Console 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

The Type System 17

C# 30

Note on Value Types


Val
Value
e types
t pes are deri
derived
ed from
y
yp
System.ValueType
Value types are sealed
Value types can override objects
methods
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

The Type System 18

C# 30

Intermediate Thoughts
Value types have a simple
simple, efficient form
form,
in which they can be handled efficiently
But all types derive from
System.Object, so they can be treated in
System.Object
common terms
This means that a value
al e ttype
pe variable
ariable can be passed
to a method that gets an object as a parameter
This should also mean that the following statements
are valid:
int i =42;
objecto=i;//???
objecto i;//???
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 19

C# 30

Boxing
Ha
Having
ing ssuch
ch different forms
forms, ho
how can a
yp variable be assigned
g
to a
value-type
reference type?
Lets
Let s explore the MSIL code generated from the two
statements above:
.locals([0]int32i,
l
l ([0] i t32 i
[1]objecto)
IL 0000:ldc i4 s42
IL_0000:ldc.i4.s42
IL_0002:stloc.0
IL_0003:ldloc.0
IL_0004:box[mscorlib]System.Int32
IL_0009:stloc.1
IL_000a:ret
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 20

C# 30

Boxing
int
i
t i =42;
42
object o=i;
Heap
Stack

System.Int32
42

42 (i)
0xdddd (o)

Note that boxing always creates a new copy of


th original
the
i i l value-type
l t
object
bj t
The two objects, i and o, now exist independently of
h other
th
each
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 21

C# 30

Unboxing
Can we retrieve a boxed value type?
int i =42;
.locals([0]int32i,
locals([0]int32i
objecto=i;
[1]objecto,
[2]int32j)
[
]
j)
int j
j=(int)o;//???
(int)o;//???
IL_0000:ldc.i4.s42
IL_0002:stloc.0
IL 0003:ldloc 0
IL_0003:ldloc.0
IL_0004:box[mscorlib]System.Int32
IL_0009:stloc.1
_
IL_000a:ldloc.1
IL_000b: unbox [mscorlib]System.Int32
IL
0010:ldind i4
IL_0010:ldind.i4
IL_0011:stloc.2
IL_0012:ret
_
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

The Type System 22

System.Object
System Object Class Members
Following are the Object class methods
methods,
that any type in .Net ultimately has:
publicvirtualbool Equals(objecto);
publicstaticbool Equals(objecto1,objecto2);
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

The Type System 23

C# 30

Comparing Two Objects


Three equality-comparing
eq alit comparing methods
And equality/inequality operators (== and !=)
publicvirtualbool Equals(objecto);
For reference types,
yp , compare
p
references
For simple value types, bitwise compare
This method can (and usually should) be overridden

publicstaticbool Equals(
objecto1,objecto2);
Calls o1.Equals(o2)

publicstaticbool ReferenceEquals(
objecto1,objecto2);
t
i
h th th
ifi d objects
bj t refer
f tto th
D
Determines
whether
the specified
the same
instance
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 24

C# 30

Comparing Objects
Class Exercise
Write next to each output operation
whether the output will be True (T) or
F
l (F)
False
(F):
usingSystem;
classCl {}
classCompareApp
{
staticvoidMain()
{
Cl cl1=newCl();
Cl cl2=newCl();
cl2 newCl();
int i =5;
int j=5;
objecto=i;
bj
i
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 25

C# 30

Comparing Objects
Class Exercise
Console.WriteLine("referenceType:");
Console.WriteLine(
"cl1==cl2:{0}",cl1==cl2);
Console.WriteLine(
"cl1.Equals(cl2):{0}",
cl1.Equals(cl2));
Console.WriteLine(
"Equals(cl1,cl2):{0}",
Equals(cl1,cl2));
l ( l
l ))
Console.WriteLine(
"R f
"ReferenceEquals(cl1,cl2):{0}",
E
l ( l1 l2) {0}"
ReferenceEquals(cl1,cl2));

______

______

______

______

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

The Type System 26

C# 30

Comparing Objects
Class Exercise
Console.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

The Type System 27

C# 30

Comparing Objects
Class Exercise
Console.WriteLine(
Console
WriteLine("misc:");
misc: );
Console.WriteLine(
"ReferenceEquals(cl1,cl1):{0}",
ReferenceEquals(cl1,cl1):{0} ,
ReferenceEquals(cl1,cl1));
______
Co so e.
Console.WriteLine(
te
e(
"ReferenceEquals(i,j):{0}",
q
( , j));
______
ReferenceEquals(i,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

The Type System 28

C# 30

System Object Members


System.Object
publicvirtual
publicvirtualint
int GetHashCode
GetHashCode();
();
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

p
publicType
publicTypeGetType
yp GetType();
yp ();
();
Returns a Type-derived object that represents the
exact runtime type of this object
The returned Type object can be used to retrieve
type 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

The Type System 29

C# 30

System Object ToString()


System.Object.ToString()
publicvirtualstringToString();
Usually returns the class name
Built-in value types return their value, string returns
the string value

For
F user-defined
d fi d ttypes
it is recommended to override this method to return a
meaningful string representing the objects state
Good 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

The Type System 30

C# 30

System Object Members


System.Object
~Object();
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,
copy a type should implement
the ICloneable interface (Clone()
Clone() method)

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

The Type System 31

C# 30

Type Conversion
The CTS defines con
conversions
ersions for basic
yp
types
It also provides means to define conversions for userdefined 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 thrown

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

The Type System 32

C# 30

Converting Basic Types


Integral types:
An implicit conversion exists only when the type to
convert to contains any possible value of the type to
convert from
An implicit conversion from float to double is allowed
allowed.
An implicit conversion from int
int,
, uint
uint, or long to float
and from long to double is allowed
Be aware that precision may be lost

An implicit conversion from integral type to decimal type is


allowed
No implicit conversion between decimal and
float/double is allowed
An implicit conversion from char to any type which can hold
unsigned short is allowed

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

The Type System 33

C# 30

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

IIn case off data


d t loss
l
during
d i th
the conversion
i
p
process
An overflow exception will be thrown

In
I case off loss
l
off precision
i i
No exception will be thrown
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The Type System 34

C# 30

Converting Strings
Reading an integer from the Console
g Convert:
using
i
int
i =Convert.ToInt
=Convert.ToInt32
32(
(Console.ReadLine
Console.ReadLine());
i ());
())

Another way is by using the Int32 static


Parse function
int i =int.Parse
=int.Parse(
(Console.ReadLine());
Console.ReadLine());

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

The Type System 35

C# 30

Chapter Summary
CTS is the foundation of the type
yp system
y
The core for the CLR cross-language support
.NET
NET basic types and their C# aliases

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

Types
T
are divided
di id d iinto
t ttwo categories:
t
i
Reference 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

Вам также может понравиться