Exploring Nullable types : Part 2

This is second and last part of the post on Nullable type series. You can view the first part from here

Exploring Nullable types : Part 1

In this series, I will talking certain rules that we need to take care while using Nullable type. I will be taking scenario wise.

First scenario:

Int? a=8;
object o = a;
long d = (long)c;

It will be compiled successfully but will throw and Invalid Cast Exception. Means, you cannot cast it to any other type except the underlying type which is here int although  int type can be hold by long.

But the below lines will run successfully

long d = (int)c;
long? d = (int)c;

Because here we are converting to an underlying type int which we can assign to long as it is a widening conversion.

Now let’s move to another point.

Second scenario:

Guess what will be the output of below lines

int? b=5;
Console.WriteLine(b.GetType());

Is it System.Nullable<Int32>. No
This actually shows System.Int32.  So beware.

Few more things:

– We can use Unary operator over Nullable type. It will be null if it has no value or null else applies the operator.

– Binary operator s also can be used with Nullable type. Give it a view

int? b=5;
int? a = 7;
Console.WriteLine(a+b);

This will print 12. But what if

 int? b=5;
 int? a=null;
 Console.WriteLine(a+b);

This will print nothing because the addition result will be null. So be sure, during any binary operation if one operand ( or does not have any value) is null. The result will also be null ( or would not have any value).
Hope both post will give you all a fair enough knowledge of Nullable types. Do share if you have some more points in this. I will add those here..

Happy C# coding.

2 thoughts on “Exploring Nullable types : Part 2

  1. Pingback: What are immuatable types | Code Wala

  2. Pingback: Using Null Conditional operators | Code Wala

Leave a comment