One big difference between value and reference type
variables is null. With a reference type, having the null value basically means
that it is not referencing anything. Value types obviously cannot ever have the
null value because we are saying that it is a special value having to do with
references.
If you have ever tried to assign the null value to a value
type, such as assigning null to an integer variable, you have probably received
a nice compiler message. This is because value types do not reference anything,
so the concept of null makes no sense for them. It is not a valid integer
value.
Nullable Types
In C# we have some special types which allow us to have our
value types as allowing nulls. These are called Nullable Types. This is not
really true the way I have described it here. The main way to obtain a nullable
type is to follow the type identifier with a question mark. So, for example, I
would define one in the following way.
Listing 2: Nullable Values
int? myNullableInteger = null;
bool? myNullableBool = null;
What I have done here is not really what it appears. I am
allowing a null value for an integer, but not really. The way this works is
that there is a struct called Nullable. It is a generic type, so really I made
Nullable<Int32> and a Nullable<Boolean> with the above statements.
The Nullable struct defines a pair of read-only properties: HasValue and Value.
HasValue is just used to check if it is null or not. If it is not null then you
are safe to check the Value.