Nullable Types

This feature was added to C# 2005. This allows us to assign value ‘null’ to a value-type variables including struct. Lets take a scenario we have an ‘age’ field which is of type int in database, the value for this field could be all the values that can be assigned to value-type int plus it could be ‘null’ value (undefined or not used or empty). This is possible using nullable type variables; we can assign the exact value of age as it is in the database to our nullable-type variable.

The nullable type is declared with the ? symbol just next to any value-type.

Value-Type? myVariable;

int age? = null;

Nullable types are instances of the System.Nullable struct. The two important Properties of the Nullable struct are HasValue and Value. In the below example, age.HasValue returns false as there is no value assigned to age int value-type.

using System;
class MyClass
{
static void Main()
{
int? age;
age = null;
int simpleInt=-1;

if (age.HasValue)
simpleInt = age.Value;

Console.WriteLine("Age is {0} Years", simpleInt);
Console.ReadLine();
}
}


We cannot create a nullable type based on a reference type.

MyClass? obj = new MyClass?(); //Error: The type 'ConsoleApplication1.MyClass' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

Nullable(T).GetValueOrDefault returns either the assigned value, if the value is not assigned (null) it will return the default value of the respective value-type, in the below example age.GetValueOrDefault() returns 0 – the defult alue for int value-type as the age is null (undefined)

int? age;
age = null;
int simpleInt = age.GetValueOrDefault();

Conditional and Null-Coalescing Operators (??):

We can assign a default value to the nullable variable using Null-Coalescing Operator (??). In the below example if age nullable type is null then the default of -1 is assigned.

using System;
class MyClass
{
static void Main()
{
int? age;
age = null;

int simpleInt = age ?? -1;

Console.WriteLine("Age is {0} Years", simpleInt);
Console.ReadLine();
}
}


Below code is used to identify nullable types.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
//...
}

type.IsGenericType is to test if the property is a generic type
type.GetGenericTypeDefinition() == typeof(Nullable<>) to know if its a nullable type

Comments

Popular posts from this blog

Convert XElement to DataTable

Enable mouse scroll-wheel in VB6

C# code to Check IE Proxy Settings