Tuesday, January 09, 2007

* CSharp : Understanding Nullable Types

Nullable Types are instances of the System.Nullable struct introduced in .NET 2.0. Null means value undefined or value not known. Reference types by design support storing null but values types have been designed to store only the range of values they are made for. They don't have capacity to store null. But many times there may be situation where we don't know the value to store in value type e.g. in case of database fields where some fields may be empty of null.

To support such requirements Nullable types have been introduced. Nullable types are supported using a Nullable Generic Structure in System Namespace.

public struct Nullable<T> where T : struct

The following struct can be used in following two ways :

Nullable<int> x = new Nullable<int> (100);

or

int? x = 100;

The two main properties of this struct are HasValue and Value.

HasValue indicates whether the current instance has a value. True if the instance has a value & false if has no value. The value in the object can be accessed by property Value.

The operator ?? can be used to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type.

e.g. int? x= null; int y = x ?? 1; y will be assigned a value of 1.

No comments:

Post a Comment