When I try to create an extension method for the File class, I get an error telling me that I cannot do this because the class is static. However, I don't see why this stops the creation of an extension method, what implication is there?
Thanks
When I try to create an extension method for the File class, I get an error telling me that I cannot do this because the class is static. However, I don't see why this stops the creation of an extension method, what implication is there?
Thanks
Extension methods are called on an instance of an object.
myObj.ExtensionMethod();
If you have a static class, you can't have an instance of it. Therefore, there's nothing to call the extension method on.
Because an extension method by design must take an instance of the class it is extending as its first parameter. And obviously you can't pass an instance of File because it is a static class and cannot have instances.
Stated in reverse, if you look at the definition of any extension method, the first parameter is always the instance of the object upon which it is called evidenced by the this
keyword. Logically this behaviour cannot work on a static class because there is no instance present.
Sample of an extension method - see first param this
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
Why can’t I create extension methods for static classes?
Because the C# dev team didn't implement that feature (yet). F# has chosen to implement it though.
Same thing for extension properties. F# has them and Boo has had them since (at least) 2006.