Why can't I create extension methods for static classes?

When I try to create an extension method for the File class, I get an error message indicating that I cannot do this because the class is static. However, I do not understand why this stops the creation of the extension method, what kind of implication exists?

thanks

+6
c # extension-methods static-classes
source share
4 answers

Extension methods are called on an instance of an object.

myObj.ExtensionMethod(); 

If you have a static class, you cannot have an instance of it. Therefore, there is nothing to call the extension method.

+8
source share

Because the design method should take an instance of the class that it extends as its first parameter. And, obviously, you cannot pass an instance of a file because it is a static class and cannot have instances.

+5
source share

In the reverse order, if you look at the definition of any extension method , the first parameter is always the instance of the object on which it is called with the this . Logically, this behavior cannot work on a static class, because the instance is missing.

An example of an extension method - see the first parameter this

 public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } 
+5
source share

Why can't I create extension methods for static classes?

Since the C # development team has not implemented this feature (yet). F # decided to implement it , though.

The same goes for extension properties. F # has them and Boo has had them since (at least) 2006 .

0
source share

All Articles