This articlemay be too technical for most readers to understand. Pleasehelp improve it tomake it understandable to non-experts, without removing the technical details.(August 2009) (Learn how and when to remove this message) |
In Microsoft's.NET Framework, theCommon Type System (CTS) is a standard that specifies howtype definitions and specific values of types are represented in computer memory. It is intended to allow programs written in different programming languages to easily share information. As used inprogramming languages, atype can be described as a definition of a set of values (for example, "all integers between 0 and 10"), and the allowable operations on those values (for example, addition and subtraction).
The specification for the CTS is contained inEcma standard 335, "Common Language Infrastructure (CLI) Partitions I to VI." TheCLI and the CTS were created by Microsoft, and theMicrosoft .NET framework is an implementation of the standard.
Whenrounding fractional values, thehalfway-to-even ("banker's") method is used by default, throughout the Framework. Since version 2, "Symmetric Arithmetic Rounding" (round halves away from zero) is also available by programmer's option.[1]
The common type system supports two general categories of types:
The following example written inVisual Basic .NET shows the difference between reference types and value types:
ImportsSystemClassClass1PublicValueAsInteger=0EndClass'Class1ClassTestSharedSubMain()Dimval1AsInteger=0Dimval2AsInteger=val1val2=123Dimref1AsNewClass1()Dimref2AsClass1=ref1ref2.Value=123Console.WriteLine("Values: {0}, {1}",val1,val2)Console.WriteLine("Refs: {0}, {1}",ref1.Value,ref2.Value)EndSub'MainEndClass'Test
The output of the above example
Values: 0, 123Refs: 123, 123
Converting value types to reference types is also known asboxing. As can be seen in the example below, it is not necessary to tell the compiler an Int32 is boxed to an object, because it takes care of this itself.
Int32x=10;objecto=x;// Implicit boxingConsole.WriteLine("The Object o = {0}",o);// prints out "The Object o = 10"
However, an Int32 can always be explicitly boxed like this:
Int32x=10;objecto=(object)x;// Explicit boxingConsole.WriteLine("The object o = {0}",o);// prints out "The object o = 10"
The following example intends to show how to unbox a reference type back to a value type. First an Int32 is boxed to an object, and then it is unboxed again. Note that unboxing requires explicit cast.
Int32x=5;objecto1=x;// Implicit Boxingx=(int)o1;// Explicit Unboxing