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:
- string str = "Hello";
- string newstr = str.RemoveVowels();
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:
- public static class ExtensionMethods
- {
- public static long GetSize(this DirectoryInfo dir)
- {
- // Initialize to zero
- long size = 0;
- // Loop through all the subdirectories and files
- foreach(DirectoryInfo folder in dir.GetDirectories())
- size += folder.GetSize(); // Recursive call
- foreach(FileInfo file in dir.GetFiles())
- size += file.Length;
- return size;
- }
- }
So one can use this method as an instance method of any DirectoryInfo instance.
- DirectoryInfo dir = new DirectoryInfo(@"C:\WINDOWS");
- long sizeOfWindowsFolder = dir.GetSize();
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!
Ya I totally agree with this fact that there has been a lot of criticism regarding Extension Methods but it's totally unfair to other developers who believe in achieving their intent using the best possible solution rather than sticking to the conventional OOP paradigm.
ReplyDeleteExtension methods is surely going to find its way in my blog as well so watch out ..
Long live Extrension methods !!!
hello... hapi blogging... have a nice day! just visiting here....
ReplyDelete