What is the design motive behind extension methods in C# - c#

I was wondering what is the design motive behind extension methods in C#

It allows you to create new functionality to an existing code base without editing the original code.
http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx
"Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework that is being introduced with .NET as part of the "Orcas" release."

The primary reason for their existence is being able to somehow add features to a type without inheriting from it.
This was required to provide Where, Select, ... methods for use in LINQ for collections that didn't have one.

It provides multiple inheritance via the back door.
It languages such as C++, which support inheriting from many classes, extension methods aren't required. However multiple inheritance has lots of problems with it, and so modern languages have dropped it. However extension methods are a use-case where multiple inheritance is useful. Rather than re-introduce multiple inheritance though, the C# designers created extension methods (which is a very neat solution to the problem).

Quite often we end up writing for ourselves usefull little utility static classes that perform a common function on a type. I know there have been a number of times I wished I could simply inherit a class to add a feature but that class is sealed. I'm glad though they were sealed, unwarranted inheriting is a bad thing.
Extension methods make code look more intuitive by allowing those static methods to appear to be new instance methods of the type.
They also have the advantage of not polluting the actual member namespace of the type and allowing you to opt into them by means of the using keyword.

The existence of Extension Methods is very likely due to the need for Microsoft to add functionality to IEnumerable without changing the interface. If they added methods to the interface, then every existing implementation of IEnumerable (including Microsoft's) would no longer compile.
The alternative to changing IEnumerable is to create a utility class (called Enumerable) which has methods that perform transformations on instances of IEnumerable. This works, except the user experience is not the same as calling a method from an existing IEnumerable instance. For instance, compare the following equivalent statements.
IEnumerable<string> strings = myIntList.Select(num => num.ToString())
.Where(num => num.StartsWith('T'));
IEnumerable<string> strings =
Enumerable.Where(
Enumerable.Select(myIntList, num => num.ToString()),
num => num.StartsWith('T'));
To achieve the best of both worlds, the C# compiler team added support for extension methods, allowing the creation of the Enumerable class with special syntax and maintaining the same user experience of having added the methods to IEnumerable to begin with.

Related

Why are extension methods used extensively in LINQ, despite the framework's guidelines?

The Extension Methods documentation says:
For a class library that you implemented, you shouldn't use extension
methods to avoid incrementing the version number of an assembly.
So why has the .NET team used them extensively in Enumerable and Queryable?
In search of a reason I checked out my copy of C# In Depth, where I came away with a feeling that extension methods are used because:
You can chain them together in a readable way
You can bring them in and out of scope
Is this correct or are the .NET team flying in the face of their own documentation? Are there other reasons that justify their use?
That's not the entire sentence. What is actually written is this:
For a class library that you implemented, you shouldn't use extension methods to avoid incrementing the version number of an assembly. If you want to add significant functionality to a library for which you own the source code, you should follow the standard .NET Framework guidelines for assembly versioning.
(emphasis added)
What this means is that you should avoid just adding extension methods to a class when you're adding large amounts of functionality, just for the sake of not incrementing the assembly version. If you're going to introduce large amounts of new functionality, you should really do it in a new version of that assembly.
It's because LINQ works on IEnumerable, not any specific implementation of a collection. If they were part of the definition of IEnumerable, you would have to implement your own methods, and it would needlessly bloat the interface. By putting LINQ into extension methods, you can implement IEnumerable on any class you create yourself, and the existing LINQ methods will work on it.

Why does Microsoft use extension methods for their own classes?

Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
There are a number of reason Microsoft did this. The two biggest being:
Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically.
For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
IgnoreRoute() on RouteCollection is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the RouteCollection class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class.
I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
This is an example of the Non-Virtual Interface pattern (similar to Template Method). This is a pattern used in languages with multiple (implementation) inheritance, and the way to do it in C# is to use extension methods.
The basic idea is that you have only non-virtual and pure-virtual (abstract) methods. The implementor of the interface (or inheritor of the class/mixin, in languages with multiple inheritance), implements a small method or set of methods (in this case, GetEnumerator), and in return gets a whole slew of methods that depend on that one abstract method (like Select, Where, Aggregate, etc.)
As Michael Edenfield said in his answer, if we want to implmeent this pattern and we want IEnumerable to be an interface, we need to use extension methods. And making IEnumerable into an abstract class would be bad because its supposed to be a very low-cost, basic interface that should be put on pretty much any collection - implementing IEnumerable should not require rethinking a class hierarchy, it should be almost "for free".
I think the main reason is that it's very easy to extend such methods. For example, if you Linq extension methods you can easily write yout own set of extension methods (maybe foreach or some specific filter) which will work greate with microsoft methods: mylist.Where(...).MyFilter(...).Select(...)
My two cents:
because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.

Should extension methods only be used on classes whose code you don't have access to?

Should extension methods only be used on classes whose code you don't have access to?
I'm struggling to come up with a reason to have extension methods versus making it partial and adding the classes in an external file.
My specific scenario is as follows: I have classes that represent entities in a database via EF. I'm debating making the classes it renders partial and adding my own methods. Are extension methods a more valid alternative approach or are they not intended to be used when you have access to the code of the class you are extending?
The canonical counter-example is extension methods on an interface, as even if you control the source, there is no implementation. See: Linq.
But, yes, generally speaking, if you control the source of the concrete class, it is not unreasonable to expect to add the functionality to the class directly rather than using an extension method, if it makes sense for the functionality to actually be part of the class instance.
On the other hand, and coming back to your situation, you might consider neither approach. Your entities are data models, I would not add methods to those models, but rather encapsulate that functionality elsewhere. Those models exist to encapsulate your data, logic that might operate with or against that data might be better served in a different unit. But that really depends upon what your methods are doing, and also assuming they're not something like a trivial wrapper over one or more properties, for example.
Apart from the ability to provide extensions to interfaces, I use extension methods to add 'members' to a class that work using only the class' public interface. So if a method needs access to a private/protected member, it will become a class member, if not an extension method. This keeps the classes themselves small and focused...
No.
You may have a class that works fine in ninety percent of your projects. By adding an extension method you don't 'pollute' the original class but can still leverage it in the other ten percent of your projects.
Should extension methods only be used on classes whose code you don't have a access to?
Not necessarily. There are situations where extension methods can still help. I recently had an issue with the xml serializer where it could serialize an object that had a method that made use of a linq / lamba expression. Moving the method to an extension method resolved that. I like to use extension methods on DTOs also.
You might want to look at How Non-Member Functions Improve Encapsulation. There are some C++ specifics, but main idea applies to other OO languages as well. In short: the less methods you have in a class the easier it is to understand who and how changes private class state.

Are extension methods an object-oriented feature of C#?

Do extension methods follow the object-oriented paradigm in C#?
Is it a good practice to use extension methods?
In the software development lifecycle how should we consider this question in the design phase?
Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:
So, yes, the oft-heard criticism that
"extension methods are not
object-oriented" is entirely correct,
but also rather irrelevant. Extension
methods certainly are not
object-oriented. They put the code
that manipulates the data far away
from the code that declares the data,
they cannot break encapsulation and
talk to the private state of the
objects they appear to be methods on,
they do not play well with
inheritance, and so on. They're
procedural programming in a convenient
object-oriented dress.
They're also incredibly convenient and
make LINQ possible, which is why we
added them. The fact that they do not
conform to some philosophical ideal of
what makes an object-oriented language
was not really much of a factor in
that decision.
I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable<T> in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.
If you accept that you've got some static utility method, which syntax would you rather use?
// Traditional
CollectionUtils.Sort(collection);
// Extension methods
collection.Sort();
The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.
Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).
Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.
What are the best practices for using Extension Methods in .Net?
Possible overuses of Extension Methods
Do Extension Methods Hide Dependencies?
There are two parts to it.
Is it OO when we use it
No; it makes you feel that you are calling method on the particular type
Is it OO based on how it is compiled/built
Yes; Compiled code has a static method using the object on which extension method was invoked
Extension methods are just a language feature. They work on object instances and are very nice tool.
Consider them as a different way to extend class functionality. You can add new functionality to a class:
By adding a partial class declaration. The class then instantly gets a bunch of new methods and properties.
By including a namespace with your extension methods holder class. The class then gets a bunch of new methods again.
Rather an organizational / language feature. Does not break object-oriented concept in any way. Just as header/source file division in C/C++ has nothing to do with object-orientation, just a language/framework feature.
It depends. Extension methods are just a tool. They can be very useful when used appropriately. But if you use them too much, it can obscure your code.
Extension Methods are just static methods that work with a specific Class or Class Hierarchy. Python is OO but has modules, Ruby has mixins. I see it more as a language feature. I am pretty sure its still OO friendly

evaluating cost/benefits of using extension methods in C# => 3.0 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ?
< full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" >
I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text.
A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands."
While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions.
Looking at MS's guidelines at link text, you find :
In general, you will probably be
calling extension methods far more
often than implementing your own. ...
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type. For more information,
see Inheritance (C# Programming
Guide). ... When the compiler
encounters a method invocation, it
first looks for a match in the type's
instance methods. If no match is
found, it will search for any
extension methods that are defined for
the type, and bind to the first
extension method that it finds.
And at Ms's link text :
Extension methods present no specific
security vulnerabilities. They can
never be used to impersonate existing
methods on a type, because all name
collisions are resolved in favor of
the instance or static method defined
by the type itself. Extension methods
cannot access any private data in the
extended class.
Factors that seem obvious to me would include :
I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ?
Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ?
How frequent use of Extensions would affect run-time performance or memory use : I have no idea.
So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing.
thanks, Bill
My greatest usage for them is to extend closed-off 3rd party APIs.
Most of the time, when a software developer is offering an API on Windows these days, they are leaning more and more toward .NET for that extensibility. I like to do this because I prefer to depend on my own methods that I can modify in the future and serve as a global entry point to their API, in the case that they change it.
Previously, when having to do this, and I couldn't inherit the API object because it was sealed or something, I would rely on the Adapter pattern to make my own classes that wrapped up their objects. This is a functional, but rather inelegant solution. Extension methods give you a beautiful way to add more functionality to something that you don't control.
Many other peoples' greatest usage for them is LINQ!
LINQ would not be possible without the extension methods provided to IEnumerable.
The reason why people love them is because they make code more readable.
I have noticed another MAJOR usage of extension methods (myself included) is to make code more readable, and make it appear as if the code to do something belongs where it is supposed to. It also gets rid of the dreaded "Util" static-god-class that I have seen many times over. What looks better... Util.DecimalToFraction(decimal value); or value.ToFraction();? If you're like me, the latter.
Finally, there are those who deem the "static method" as EVIL!
Many 'good programmers' will tell you that you should try to avoid static methods, especially those who use extensive unit testing. Static methods are difficult to test in some cases, but they are not evil if used properly. While extension methods ARE static... they don't look or act like it. This allows you to get those static methods out of your classes, and onto the objects that they really should be attached to.
Regarding performance..
Extension methods are no different than calling a static method, passing the object being extended as a parameter... because that is what the compiler turns it into. The great thing about that is that your code looks clean, it does what you want, and the compiler handles the dirty work for you.
I use extension methods as a way to improve the functionality for classes without increasing the complexity of the class. You can keep your classes simple, and then add your repetitive work later on as an extension.
The Min() and Max() extension methods are great examples of this. You could just as easily declare a private method that would calculate these, but an extension method provides better readability, makes the functionality available to your entire project, and didn't require making an array any more complex of an object.
Taking the sub-classing approach vs. extension methods requires a couple of things to be true
The type must be extendable (not-sealed)
All places the type is created must support a factory pattern of sorts or the other code will just create the base type.
Adding an extension method requires really nothing other than using a C# 3.0+ compiler.
But most importantly, an inheritance hierarchy should represent an is-a relationship. I don't feel that adding 1 or 2 new methods / behaviors to a class truly expressing this type of relationship. It is instead augmenting existing behavior. A wrapper class or extension method much better fits the scenario.
In some cases you can't use a subclass: string for instance is sealed. You can however still add extension methods.

Categories

Resources