Saturday, August 28, 2010

C#.net - Nullable Type

Nullable Type

.NET 2.0 introduced Nullable value types. As you surely know by now, you cannot set a value type to null.

 
int val = null; //this statement give error because it cannot convert to int because it is a non-nullable value type

This can be easily solved by transforming val into a Nullable type:

 
Nullable<int> val = null;

Or you can apply the ? suffix to the variable type:

int? val = null;

How can we check if our nullable value type contains data?
if (val.HasValue)
{
    System.Console.WriteLine("System.Nullable<T> Object have a value");

     // get the value from a nullable object

     System.Console.WriteLine("Value : " + val.Value);
}
else
{
     System.Console.WriteLine("System.Nullable<T> Object dose not have a value");   
}

Full Example on Nullable Type

Step 1
Create a Console application

Step 2
Add the following code snippet on console application,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NullableType
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int? val = 11;

                // Check the System.Nullable<T> object have a value or not
                if (val.HasValue)
                {
                    System.Console.WriteLine("System.Nullable<T> Object have a value");

                    // get the value from a nullable object

                    System.Console.WriteLine("Value : " + val.Value);
                }
                else
                {
                    System.Console.WriteLine("System.Nullable<T> Object dose not have a value");   
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);    
            }
        }
    }
}

Run the Project

Download
Download Source Code

No comments:

Post a Comment