cescamilla

Nullable types in C#

Discussion created by cescamilla on Feb 9, 2009
Latest reply on Mar 28, 2009 by cescamilla

One of the features I miss the most from C/C++ is actually the ability of a variable to not have a value!

 

Yeah, I used to depend on a variable's ability to tell me "Hey, I have not been assigned a value yet" and do something accordingly. But now, with C#'s strict typing and the fact that everything is an object and therefore is initialized as soon as it is created. So even if you did not ask for an integer to be zero it will be as soon as it is created. So let's welcome the null-able types! (notice my excitement).

 

 

 

Defining an integer in C#:
int iSomeValue; //this will create an int object with zero

 

Defining a nullable integer in C#:
int
? inOtherValue; //this will create an int object with null

 

Now everything is good so far, but if you try to set iSomeValue to inOtherValue the compiler will complain about a cast being needed! Here is how to use them:

 

if (inOtherValue.HasValue == true) {
  iSomeValue = (int) inOtherValue;
} else {
// do something as asking the user for a value
  // or returning as no value could be found

}

 

As usual, I do preffer working with ints, so, here it is the way to box and unbox a int? to make it an int.

 


if (inOtherValue.HasValue) {
  iSomeValue = (int)(object)inOtherValue;
  // now we can use iSomeValue as normal.
}

 


That's it!! this is one of those features I did really miss, and even if this seems too cumbersome to manage I do welcome the fact that it is (at least) available... I figured a lot of scenarious it was great at!

Outcomes