The C Type System


The C# Type System

Reference Versus Value Types

The type system of the Common Language Runtime is divided into two worlds . Reference types are heap-allocated types and are used for most objects. Value types are either stack-allocated or allocated as part of another object; they are used for the predefined numeric types and other types that "feel like data."

This two-type system presents a problem for languages such as C#, which wish to present a unified type system where possible. If reference types and value types remained in separate worlds, it wouldn't be possible to write something like the following:

 int value = 55;  double precision = 0.35; Console.WriteLine("Result: {0}, {1}", value, precision); 

For this code to work would require an overload of WriteLine that took a string , an int , and a double .

The runtime environment provides a way to make a value type look like a reference type, known as boxing. A box is simply a reference type wrapper for a value type that allows it to be passed around like any other reference type, as a parameter of type object .

C# chooses to make boxing as transparent as possible, so there is no explicit box operation; when a user uses a value type in a location where boxing is required, [4] the compiler automatically generates the boxing code. This allows the user to write something like

[4] Either by assignment to type object or by casting it to an interface.

 Console.WriteLine("Result: {0}, {1}", value, precision); 

without caring whether the arguments are reference types or value types.

Once a value type has been boxed, the instance is opaque from the C# standpoint; there is no difference between a boxed integer, a boxed double, and a boxed user-defined value type. This simplifies the user model, but it also means that there is no way to modify the value of a boxed instance without unboxing it to the original type, modifying the value of the original type, and reboxing it. This has some performance implications when storing boxed value types in collection classes.

User-Defined Types

In C#, reference types are written using the class keyword, and value types are written using the struct keyword. Although value types inherit implicitly from type object , they do this only through boxing. Value types are therefore intended for writing types such as complex numbers , BigNums, or vectors.

C# also allows defining interfaces with the interface keyword, and enumerated constants and bit flags can be defined using the enum keyword.



Programming in the .NET Environment
Programming in the .NET Environment
ISBN: 0201770180
EAN: 2147483647
Year: 2002
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net