Logo: C# Computing
 
Web CsharpComputing.com

C# Tutorial Lesson 7: Reference types

In the Types overview lesson, we have encountered a class, integers and strings and discussed value and reference types. In this lesson we will continue to study the class and will also study it's nameless sibling - boxed value.

Class is the workhorse of C# and is the most commonly used user-defined reference type. Here is a definition of a Calculator class:

class Calculator{ int Add(int x, int y); }

A class needs to be declared:

Test mTest;

and a concrete class needs to be allocated

mTest=new Test();

An instance of a class is called an object.

A C# class is allocated on the heap and is cleaned up by the garbage collector when the object is no longer needed.

When the object is created, all of its field are allocated on the heap - this includes both value and reference types with the object.Class declaration is a pointer from the stack to the heap.

Larger objects take longer to allocate for two reasons: 1. Larger classes contain more fields each of each needs to be created. 2. Allocation of larger classes might require a garbage collection to make more space available for the new object.

When instantiating an object with empty parentesis, we are said to be invoking a default constructor for that object. Default constructor is declared as method of class that has not return types and takes no arguments. Default constructor always has the same name as the class e.g.

class Test{
 Test()  {}
}

When an object is constructed all of its fields are set to defaults. Defaults for numeric types are zeros. Defaults for reference types are nulls. A null reference type simply means that the memory has not been allocated yet for the type. Structures are allocated on the stack at compile time with members of the structure in the stack's memory space. Structures have no default (e.g never null) because they are not associated with any variable pointing to them.

While classes provide named wrappers to value types. C# also supports unnamed reference wrappers to value types. Unnamed wrappers are called boxed values.

int x=3; object y=(object)x;

Two golden rules of boxing are: -There is no way to extract value from the boxed object without unboxing it. -Boxed value can only be unboxed into the same type.

e.g.

long z=(long)y; gives InvalidCastException

Delegates are also reference types, we will cover delegates in Lesson14.

An array is another important reference. Array size is fixed at allocation time. Try to access an array element that is out of range results in OutOfRangeException. Array range checks are built into safe array access. Inclosing array access code into an unsafe code block results in significant performance improvement for 1 dimensional arrays.

Unless you are working on a high performance scientific application, you should not worry about .NET underperforming C++ - it is not noticable in standard business applications.