Digbyswift is based in Leeds, West Yorkshire offering web and digital solutions. With over a decade of experience in corporate and agency web development, Digbyswift can meet and support your requirements, whether it be MVC or web forms development, Umbraco, bespoke CMS build and maintenance, ecommerce, SEO and Google analytics or even client training. Read more ...

.Net Extension Methods

By Digbyswift at November 06, 2009 11: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.