Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't static method in non-static class be an extension method? [duplicate]

Tags:

Possible Duplicate:
extension method requires class to be static

In .NET:

Why can't static method in non-static class be an extension method?

like image 477
Yaakov Shoham Avatar asked Sep 13 '11 17:09

Yaakov Shoham


People also ask

Can a static class extend a non-static class?

Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. You can extend static inner class with another inner class.

Are extension methods always static?

Here, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name. Extension methods are always defined as a static method, but when they are bound with any class or structure they will convert into non-static methods.

Why extension methods are static?

Extension methods are static because they get the instance passed in via the first parameter, and they don't act on the actual instance of their declaring class. Also, they're just a syntactic sugar. CLR doesn't support such a thing.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.


2 Answers

It makes sense that a static class is required to have extension methods. The number one reason is that the static class is stateless ...i.e. you don't have to instance the class. ...but this is just my gut feeling. It wouldn't make sense to me otherwise.

I think, too, that forcing extension methods to reside in public/internal static classes reduces the cost of using them.

like image 31
IAbstract Avatar answered Oct 04 '22 02:10

IAbstract


Eric Lippert will probably weigh in with a really good answer on this one, but the gist of it will probably be:

We decided it would be easier on both programmers and the compiler if we limit the number of places that you have to look for extension methods.

This policy tends to force users to put all of their extension methods into a few specific classes that are designated for this purpose.

like image 58
StriplingWarrior Avatar answered Oct 04 '22 02:10

StriplingWarrior