Nullable Type in c#

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
                                           .NET 2.0 introduced Nullable value types. As you surely know by now, you cannot set a value type to null.

                                               
int x= null; //this statement give error because it can not convert to int ,its a non-nullable value type

This can be solved by following code

Nullable<int> x = null;

or you can use suffix '?' also like

int? x = null;

we  can check if our nullable value type contains data with the use of following code

if (x.HasValue)
{
  Console.WriteLine("x have a value");

  // get the value from a nullable object x

    Console.WriteLine("X : " + x.Value);
}
else
{
     System.Console.WriteLine("x dose not have a value");   
}



Ebook Download
View all
Learn
View all