.Net Extension Methods

By Digbyswift at November 06, 2009 06:57

Two words. Code re-use.

Think of a specific, probably basic bit of code that you find yourself writing a lot, e.g. validating a string to ensure it is either null or not empty. Generally you’d have to write:

if (value == null) 
    return null; 

value = value.Trim(); 
return (value.Length == 0) ? null : value;


Using extension methods, you can wrap this in a tidy method:

public static string TrimToDefault(this string value) 
{ 
    if (value == null) 
        return null; 

    value = value.Trim(); 

    return (value.Length == 0) ? null : value; 
}

I also overload this so that I can specify a default value:

public static string TrimToDefault(this string value) 
{ 
    return TrimToDefault(value, null); 
} 

public static string TrimToDefault(this string value, string defaultValue) 
{ 
    if (value == null) 
        return defaultValue; 

    value = value.Trim(); 

    return (value.Length == 0) ? defaultValue : value; 
}

I can then implement the methods like so:

string stringToSave = txtTitle.Text.TrimToDefault();

or

string stringToSave = txtTitle.Text.TrimToDefault("Not specified");


Alternatively, you can overload existing methods. So you could simply overload String.IsNullOrEmpty().

You might say, that this isn’t really a time saver but the value is that if you have a library of such methods you can maintain consistency across different projects but also enforce a little consistency in the way fellow developers on your team code too. This will save you time.

Lovely.

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading



Kieron McIntyre

C# .Net Developer, based in Leeds. Married, happy and always learning