22 September, 2012

Extension method to check Null or Not Null in C#


we follow to check null reference.

if (o != null)
{    //Do Something}else{    //Do Something completely different}


but we follow extension method then make it easy coding like.

public static class ExtensionCommon  {    public static bool IsNull(this object obj)    {      return obj == null;    }     public static bool IsNotNull(this object obj)    {      return obj != null;    }     public static bool HasValue(this string obj)    {      return !string.IsNullOrWhiteSpace(obj);    }  }

and do code like that

if (obj.IsNotNull)
{    //Do Something.}else{    //Do Something.}

OR
if (!obj.IsNull)
{    //Do Something.}else{    //Do Something.}


No comments:

Post a Comment