C# Handy extension methods to check if a value/object is set or not

1 comment
I really dislike writing these statements:

 

if(!string.IsNullOrEmpty(param.ID))

      ….something

 

earlier I made an extension method for this:

public static bool IsNullOrEmpty(this string test)

{

    return String.IsNullOrEmpty(test);

}

 

which gives you nicer code like this

 

if(!param.ID.IsNullOrEmpty())

      …. something 

 

 

I usually make this as well:

public static bool IsNotNullOrEmpty(this string test)

{

    return !String.IsNullOrEmpty(test);

}

 

giving:

if(param.ID.IsNotNullOrEmpty())

      …. something

 

 

 

But today I was checking parameters on a webservice and started to want these methods for all my parameteres, so here goes:

public static bool IsNull(this object @object)
{
    
return @object == null;
}

 

public static bool IsNullOrDefault<T>(this T value)

{

    return value.IsNull() ? true :  trueEqualityComparer<T>.Default.Equals(value, default(T)) ;

}

 

this returns true if

object == null

int == 0

bool == false

etc.

 

 

Then I didn't quite like the way it looked in code:

 

if(!param.ID.IsNullOrDefault())

      …. something

 

 

 

so I made a couple of aliases:

 

public static bool ErSatt<T>(this T value)

{

      return value.IsNotNullOrDefault();

}

 

public static bool ErIkkeSatt<T>(this T value)

{

      return value.IsNullOrDefault();

} 

 

that's nice in norwegian, in english they could be named something like:

 

public static bool IsSet<T>(this T value)

 

public static bool IsNotSet<T>(this T value)

 

 

 

Anyhow I can now write the first line:

 

if(!string.IsNullOrEmpty(param.ID))

      ….something

 

like this

 

if(param.ID.ErSatt())

      ….something

 

 

 

or in english:

 

if(param.ID.IsSet())

      ….something

 

 

 

much more intuitive in my book ;)

 

rgds

HM

Posted via email from Henris blogg

1 comment :

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete