Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Extension Methods Architecture Question

I recently asked this question: Compiler error referencing custom C# extension method

Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...

If and Extension method must be placed on a Static Class and the method itself must 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 an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...

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

like image 277
Sergio Avatar asked Dec 22 '22 12:12

Sergio


1 Answers

I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.

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

which enables LINQ:

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

With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.

As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.

like image 61
Marc Gravell Avatar answered Jan 14 '23 21:01

Marc Gravell