C # Extension Methods Architecture Question

I recently asked this question: Compiler error referring to special C # extension method

Mark Gravel's answer was perfect, and he solved my problem. But I had something to think about ...

If the Extension method should be placed in the Static Class, and the method itself should be static, why can't we create a static extension method?

I understand that the parameter marked as "this" will be used to allow access to the instance of the object that we are expanding. What I don't understand is why the method cannot be static ... it seems to me that this is a meaningless restriction ...

My question is: why can't we create an extension method that will work as a static method?

+4
source share
4 answers

I expect the real answer will be simple: there was no good use case. For instances, the advantage is that it allows you to freely pass the API on existing types (which by themselves do not provide logic) - i.e.

var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First(); 

which allows LINQ:

 var foo = (from x in data where x.IsActive order by x.Price select x).First(); 

With static methods, this is simply not a problem, so there is no excuse; just use the static method for the second type.

Be that as it may, extension methods are not object oriented - they are pragmatic abuse to make life easier due to cleanliness. There was no reason to dilute static methods equally.

+7
source

Since this function does not exist in C #.

As a workaround, static methods can be implemented in another class and called through this class to provide added functionality.

For example, XNA has a MathHelper class, which ideally would be a static extension to the Math class.

The community asks if we think this is a good idea for C # 4.0

+3
source

My thinking would be compatible - if you suddenly introduced all the extension methods of static methods with the need for this operator, you could inadvertently break the code that now overrides the normal method using the extension method.

This parameter allows you to control and, thus, does not violate compatibility.

Just an idea.

+1
source

First of all, you need to add one more syntax to indicate that you want to extend the static methods of an existing type. With extended syntax, you really need a very good reason.

Suppose I have a MyExts class that allows me to add extension methods to MyClass. Why: -

 MyClass.DoSomethingExtra(); 

better than

 MyExts.DoSomethingExtra(); 

?

0
source

All Articles