background image

Custom Types

<< .NET type system | Boxing and Unboxing Value Types >>
<< .NET type system | Boxing and Unboxing Value Types >>
The primary difference between reference and value types is how instances of the
two types are treated by the CLR. One difference is that the GC collects instances of
reference types that are no longer referenced by the application. Instances of value
types are automatically cleaned up when the variable goes out of scope. Let's take a
look at an example in VB.NET:







Another difference is when one variable is set equal to another or passed as a
parameter to a method call. When a variable of a reference type (A) is set equal to
another variable of the same type (B), variable A is assigned a reference to B. Both
variables reference the same object. When a variable of value type (A) is set equal
to another variable of the same type (B), variable A receives a copy of the contents
of B. Each variable will have its own individual copy of the data.

Yet another difference between the behaviors of value types versus reference types
is how equality is determined. Two variables of a given reference type are
determined to be equal if both the variables refer to the same object. Two variables
of a given value type are determined to be equal if the state of the two variables are
equal.

The final difference between the two is the way the instances of a type are initialized.
In a reference type, the variable is initialized with a default value of Null. The
variable will not reference an object until explicitly done by the object. Whereas a
variable declared as a value type will always reference a valid object.

Custom Types
A Custom Type is a set of data and related behavior that is defined by the developer.
A developer can define both custom reference type and custom value types.
In vb.net we can define custom types by using the Structure keyword. Let's look at
an example wherein we define a custom value type.
Sub Test()
Dim myInteger as Integer
Dim myObject as Object
End Sub

`myInteger a Value type is automatically cleaned up when the Sub ends.
`But myObject a Reference type is not cleaned up until the GC is run.