Wednesday, April 21, 2010

Defining Nullable Types in C#

Explaining it from very basic that a nullable data type is the one that can contains the defined data type or the value of null.Defining a nullable type is basically similar to defining the equivalent non-nullable type having single difference is in the use of the ? Type modifier.

As to define an integer, simply this declaration will be fine:
int simpleInt = 1;

But to make it able to store null value or to become a nullable datatype,we need to declare it as:
int? simpleNullableInt = 1;

The nullable version is actually a structure that consists of a value type and with a flag to indicate whether the value is null. Being more specific, a nullable type has two publicly readable properties, HasValue and value. HasValue is simply a bool variable that is true if there is a value stored otherwise, it is false if the variable is null. If HasValue is true, you can get the value of the variable. If it is false and you attempt to get the value definetly an exception will be thrown. null is now become a keyword for C#. Adding more words to it, it can be assigned to a nullable variable. The following are two valid assignments for a nullable variable:
double? simpleDouble = 3.14159;
double? simpleOtherDouble = null;


As simpleDouble is assigned a value, but could also be assigned null and in the second statement, simpleOtherDouble is initialized to contain a null value—something you can't do with a non-nullable type. A nullable type can be used in the same way that a regular value type can be used. But be sure that it doesn't have null value. Implicit conversions are built in for conversion between a nullable and non-nullable variable of the same type. It means we can assign an integer to a nullable integer and vice versa.

-
I know its a bit story about nullable datatype, But don't worry in future I will add more details to this story..
-
*The Big Short: Inside the Doomsday Machine

1 comment:

  1. This is the defination of nullable types. But, why there is need to have these type?

    ReplyDelete