Nullable Integer in C#


I was working on a codeblock yesterday , and suddenly there was an integer value assigned in the  fashion as stated below
int? FileId=null;

This kindof got me going on google to look for what it actually meant.. After reading bits and pieces about this . I tried to write a code which will help me understand the use of it.
The code is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        int? number = null;

        if (number.HasValue == true)
        {
            Response.Write("The value is Something ");
      }
        else
        {
            Response.Write("The value is Nothing ");
        }


    }
}

So what happens when we run this particular C# Snippet .. It displays me “The value is Nothing ‘ as my output .
Now how do I get this ? Well  you see we have int? number=null;  assigned . Here int? means nullable type of integer Datatype , which can allow null values . This can be very useful when working with Databases where we have a coloumn which store null values .
Now consider I Change my logic a bit to have my number value as 5000  
        int? number = 5000;

Here the output would now be “The Value  is Nothing “

No comments:

Post a Comment