Extension methods are defined as static methods, but are invoked as instance methods. This is achieved by prefixing the this keyword to the argument passed in the static method. For example, an extension method meant to remove vowels in a string would have a definition like:
public static string RemoveVowels(this string str)and it would be invoked as:
A better, more complete example should make matters clearer. In an earlier post, the DirectoryInfo class has been explained, and as has been pointed out, it does not have a method or property which returns its byte size unlike the FileInfo class. So, one can write a method to extend the DirectoryInfo class as under:
So one can use this method as an instance method of any DirectoryInfo instance.
Visual Studio 2008 provides IntelliSense support for extension methods, which makes the job of using extension methods very easy. Programmers vary in opinion about the concept of extension methods with most programmers terming it as "advantageous" while some programmers terming it as "a slap in the face of all serious software programmers". I say, as is with everything in technology, it's all up to you, sir!