How to Perform Boxing On Nullable Types
in C# (C Sharp)
C# provides
unified type system where in both value types and reference types are
derived from System.Object. However value types are primitive in nature
and they do not act as objects thereby eliminating overhead. When they
have to be treated as objects, you can explicitly do so by using boxing
and unboxing concepts of C#. Most of you will be already familiar with
these concepts; anyways here is a simple example to recall its usage:
class sampleClass
{
public static void Main() {
int intVar = 10;
Object obj = intVar; //Boxing
intVar = (int) obj; //Unboxing
}
}
In this example,
you perform boxing to convert value type intVar to an Object by direct
assignment statement. You then convert the object to an integer variable
by casting. Here unboxing is performed. Same logic can be incorporated
on nullable types as well. Assume that the integer variable intVar is
nullable, then how will you implement boxing and unboxing? Not much of
difference. Here is the modified version of code:
Its
more or less the same code, where in intVar is defined as nullable type
and when you perform unboxing, you cast the object obj with int? instead
of int. Other than this, there is a behavioral difference as well. When
you are performing boxing on a nullable type, the value gets assigned
to the object only if the value type has a definite value assigned to
it. If the variable is assigned with the value null, then boxing will
not happen. Instead the object will be assigned with the value null. Here
is an example to demonstrate this case.
In this example
since intVar is assigned with the value null, boxing will not happen for
the Object obj and it will be assigned with the value null. However intVar2
has a value 10. Hence obj2 will be assigned with the value 10. From this
example it is evident that both intVar and obj will contain its value
as null. Hence both the nullable variable and its corresponding object
are equivalent.
Note that
nullable types can be represented in a different way other than ?
symbol. The alternate way is demonstrated below:
class sampleClass
{
public static void Main() {
System.Nullable intVar = 10;
Object obj = intVar; //Boxing
}
}
System.Nullable
is equivalent to <type>?. Boxing is done in the same way for System.Nullable
variables as you do for <type>? variables.