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.
in that case how do we write in place of
int y = x ?? null;