Tuesday, May 11, 2010

Nullable Variable -C# declare as - int?

Defines a nullable int-(int?)


When int is declared as (int?) means that it contains special value of 'null', means it contains no value at all!

Defining a nullable type is very similar to defining the equivalent non-nullable type. The difference is in the use of the ? type modifier. To define an integer, you normally would do a simple declaration:

int vInt = 1;

To make vInt able to store a null value, you would declare it as such:

int? vIntNullable = 1;

For example:

int? vIntNullable = null; // vIntNullable is null,or- not even zero

vIntNullable = 0; // i is now equal to zero

Any value type variable can be made nullable by including an '?' after its name.

double? d = null; // defines a nullable double with no value

(variable?) is actually a shorthand for a variable of the generic type System.Nullable where V is any value type. This structure has two properties:

1. 'HasValue' of type bool which defines whether the nullable type has a value or not.

2. 'Value' of type V which defines the value if it has one.

A nullable type can be used in the same way that a regular value type can be used. In fact, implicit conversions are built in for converting between a nullable and non-nullable variable of the same type. This means you can assign a standard integer to a nullable integer and vice versa:

int? iOne = null;

int nTwo = 2;

iOne = nTwo; // Valid

iOne = 123; // Valid

nTwo = iOne; // Also valid

iOne = null; // Valid

nTwo = iOne; // Exception, Second is nonnullable.
Share:

0 comments:

Post a Comment