26 October 2011

Nullable value types

Some times, we came to a situation where we need to put null value into a Integer variable, or into any other value types( We can take an example of database operations, it may possible that even Bool(bit) column in table contains null value.)

In such situation Nullable types comes into picture.

What exactly Nullable types are:

  • Its an instance of System.Nullable struct
  • It just represents a value type which even can be assigned to a null value.

public class NullableTypesTest
    static void Main()
        Nullable<int> IntPriNumber=null;
        if (IntPriNumber.HasValue == true)
            System.Console.WriteLine("Varibale has value and its "+IntPriNumber.Value);
            System.Console.WriteLine("Varibale dont have a value");

Some points about Nullable types:

  • We cannot create Nullable types based on reference types.
  • Nullable types have some important 
    • properties like 
      • HasValue - returns true/false indicating variable contains value or not.
      • Value - return the value it contains.
    • methods like
      • GetValueOrDefault() - return default value in case of variable contains null value,
             Nullable<int> x=55;
             //Print 55
             Nullable<int> y=null;
             //Print 0
  • Alternative way of defining nullable types is
    T? variable=some value
    where T is a value type.
    int? temp=55

No comments:

Post a Comment

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...