Aug 19, 2015

Nullable Types in C#.NET

  • Nullable<T> type is also a value type.
  • Nullable Type is of struct type that holds a value type (struct) and a Boolean flag, named HasValue, to indicate whether the value is null or not.
  • Since Nullable<T> itself is a value type, it is fairly lightweight. The size of Nullable<T> type instance is the same as the size of containing value type plus the size of a boolean.
  • The nullable types parameter T is struct. i.e., you can use nullable type only with value types. This is quite ok because reference types can already be null. You can also use the Nullable<T> type for your user defined struct.
  • Nullable type is not an extension in all the value types. It is a struct which contains a generic value type and a boolean flag.
For example,
Nullable<int> i = 1; Nullable<int> j = null;

Use Value property of Nullable type to get the value of the type it holds. As the definition says, it will return the value if it is not null, else, it will throw an exception. So, you may need to check for the value being null before using it.

Console.WriteLine("i: HasValue={0}, Value={1}", i.HasValue, i.Value); 
Console.WriteLine("j: HasValue={0}, Value={1}", j.HasValue, j.GetValueOrDefault());  
//The above code will give you the following output:
 i: HasValue=True, Value=5
 j: HasValue=False, Value=0



Conversions and Operators for Nullable Types

C# also supports simple syntax to use Nullable types. It also supports implicit conversion and casts on Nullable instances. The following example shows this:

// Implicit conversion from System.Int32 to Nullable<Int32>
 int? i = 5; // Implicit conversion from 'null' to Nullable<Int32> 
 int? j = null; // Explicit conversion from Nullable<Int32> to non-nullable Int32
 int k = (int)i; // Casting between nullable primitive types

No comments:

Post a Comment