C# : Working with nullable operator (datetime, int,..etc)

Nullable operator make datatype Nullable (means store null value). 

In c#, sometimes we have to need use datetime as nullable . But Datetime is value type.so we don’t have choice create datetime nullable . 

Let’s do datetime nullable. 


There are two ways to make DateTime nullable 
  1.  Nullable 
  2.  System.DateTime.MinValue 
By Default. DateTime is value type so we can’t make it Nullable. 

In C# 2.0 , we can achieve this with Nullable operator . 

Using question mark (?). DateTime? Dateval=null;

public ActionResult About()
{
    DateTime? dateValue = null;

    dateValue = DateTime.Now;
    if (dateValue != null)
    {
       return View("Index");
    }
    else
    {
       return View();
    }
}

We can also make int nullable with  Nullable operator  as
 public ActionResult Test(int? id)
 {
    int? testint = id;
    ViewBag.ID=id;
    return View("Index");
 }


Tricks Always Work

Comments

Popular Posts