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

No comments
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

No comments :

Post a Comment