One interesting feature of C# is the ability to add extension methods to classes without altering the class itself. You could use this technique to add utility methods to built-in classes for use in your project.
For example, say in our project we have to remove whitespace from strings all the time. So often that we created a method to do this in a utility class..
public class Utilities
{
public static string RemoveWhitespace(string aString)
{
Regex whitespaceRegex=new Regex(@"\s*");
return whitespaceRegex.Replace(aString, "");
}
}
Then, you could call this method like this:
string myString=”a b c d e f g h i”;
string noWhitespaceString=Utilities.RemoveWhitespace(myString);
With extension methods, you can actually extend the string class itself so that you can call the RemoveWhitespace method just like any other method in the string class. To do this, we need to create a static class to put our method in and we can declare our class and method in the following way:
public static class ExtensionMethods
{
public static string RemoveWhitespace(this string aString)
{
Regex whitespaceRegex=new Regex(@"\s*");
return whitespaceRegex.Replace(aString, "");
}
}
Now, you can replace whitespace like this:
string myString=”a b c d e f g h i”;
string noWhitespaceString=myString.RemoveWhitespace();
This example is pretty trivial, and maybe not the most useful, but it demonstrates the power of extension methods. The LINQ query operators are actually extension methods giving query functionality to the pre-existing IEnumerable types. To read more about extension methods, go
here.