Friday, December 5, 2008

 

?, ?? and Casting

I have previous written a post on the use of the ? and ?? operators and nullable types. If you recall, you can make any value type by declaring it with the ? operator:


int? myIntA;
 

Also, you may recall that when you use the value of a nullable type, you must also supply a value to use if the value of the nullable type is null. If you think about it, this makes perfect sense. If myIntA was null in the example above, what the heck does it mean to 100 to myIntA? The compiler has no idea, so you must tell it, which is really one of the main reasons why the ?? operator was added.


int myIntB = 100 + (myIntA ?? 0);
 

But what if you already know the value is not null? Do you still have to supply a "dummy" value to use for null even though you know it will never be used? The answer is no, because you could always cast it to a non-nullable type:


if (myIntA == null)
{
myIntB = 100;
}
else
{
myIntB = 100 + (int)myIntA;
}
 

The casting approach is not so handy in the example above because it's just a more verbose way of doing the same calculation, but it does illustrate the point. And, there are many times, where the casting is the way to go. For example, what if you wanted to call a different method based on whether the value was null or not?



if (myIntA == null)
{
Method1();
}
else
{
Method2( (int)myIntA );
}

 

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]