
How to Perform Boxing On Nullable Types
|
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:
class sampleClass
{
public static void Main() {
int? intVar = 10;
Object obj = intVar; //Boxing
intVar = (int?) obj; //Unboxing
}
}
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.
class sampleClass
{
public static void Main() {
int? intVar = null;
Object obj = intVar; //Boxing
int? intVar2 = 10;
Object obj2 = intVar2; //Boxing
}
}
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.
_______________________________________________________________________
FREE Subscription
Subscribe
to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.
Note
: We never rent, trade, or sell my email lists to
anyone.
We assure that your privacy is respected
and protected.
Visit .NET Programming Tutorial Homepage
______________________________________________________