Can I have null assigned to an int ?

Well in .net 1.1, obviously NO! “int” is a value type and “null” cannot be assigned to a value type. Well what to do then? Interestingly in .net 2.0 we can have nullable value types by simply declaring a variable as:

int  x = null;        //Cannot convert null to ‘int’ because it is a value type

int? x = null;        //Allowed

Pretty cool way of declaring nullable value types. Wait there’s a bit more to add here. How would you check if some variable has a value of “null” or not?

You might be thinking of writing something like:

Console.WriteLine((x != null? 1 : 0));

How about writing it like this:

            Console.WriteLine((x ?? 0));.net 2.0 introduces a new operator “??” which is called as “null coalescing operator”. As you can see it’s a very powerful operator as it provides you the “null checking abilities” in your code. It works by the following rule of thumb: “Return the first value if not null otherwise simply return the second value if null”. MSDN describes it as “The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.”

Another interesting thing to note is that if you have a nullable type and you want to assign it to a non-nullable type then you need to make use of the “??” operator. Otherwise the compiler will generate an error. For example if I write as:

int y = x; //Cannot implicitly convert type ‘int?’ to ‘int’. An explicit conversion

                        exists (are you missing a cast?)

Now if you use the cast here and the nullable type is undefined i.e. null then an InvalidOperationException exception will be thrown.


One thought on “Can I have null assigned to an int ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s