This question already has answers here:
When do you use extension methods, ext. methods vs. inheritance?
(7 answers)
Closed 9 years ago.
I have been using C# extension methods for a while now and I find them to be really handy. However I am not really sure of what is the most ideal situation to use them, I feel at times I abuse them. When would you recommend the use of extension methods ?
IMO when either it's really an extension (and not a core/critical operation), or when it's a shortcut.
An example of an extension:
Often in sandbox applications (but it could also be used in real ones, of course) is extending IEnumerable with a Print method.
The print method shouldn't be there (that is: it shouldn't be a part of the IEnumerable class), but it's helping and making the syntax easier and cleaner. Also, you probably wouldn't want to ship a library with it as a part of that class.
An example of a shortcut:
Another thing I find myself often creating is an helper extension for objects with containers. Instead of calling Items.Add and similar, I just make an AddItem extension-method.
Something to consider is that it's just syntactic sugar, that is, it's for the you - the developer. So for .NET types and such use it when you think it's a good idea and will make things cleaner.
When it comes to "Should this method be an extension or a member?" see the first sentence in this answer, and also look here & here for more information.
Related
This question already has answers here:
Extension methods versus inheritance
(9 answers)
Closed 6 years ago.
I am facing this question regularly in interview. But I am not getting it's answer anywhere.Please help me.
Inheritance and extension methods are entirely orthogonal. It's just a simple way of writing a function in C# using the familiar . syntax. They only look similar if you use inheritance for code reuse, which tends to be frowned upon (but make sure you understand why - "best" practices are context-sensitive :)).
In any case, I'd expect the question is there to get you talking. Don't focus too hard on what the "right" answer is - just outline what inheritance is used for according to you, and what extension methods are used for, and what benefits and drawbacks each of those has. Get the dialog running.
For me, for example, extension methods are all about making common functions against an interface. That is, the functions add functionality on top of an interface (or class) while only using its public interface. This makes the "size" of the interface available to the function much smaller, which in turn makes it much easier to reason about.
Different people use extension methods differently, just like different people use inheritance differently. However, I find that as you shift from inheritance to composition, extension methods become more and more useful (and really, natural). Inheritance is a very specific technique that started being used for pretty much everything with little reason, but that's a big topic on Programmers.SE already anyway, just like the composition vs. inheritance debate :))
This question already has answers here:
Extension methods require declaring class to be static
(1 answer)
Why are extension methods only allowed in non-nested, non-generic static class?
(3 answers)
Closed 9 years ago.
I mean, I'm pretty sure it is a good habit anyway, but are there any technical/conceptual reasons why this is enforced by the compiler? Or is it enforcing aesthetics only?
There are no reasons for this behavior below the C# layer. Starting with the IL layer extension methods and static classes do not exist (except for either unimportant changes or custom attributes).
It is a choice the language designers made, supposedly for code clarity. It does not have to be this way for any fundamental reason.
There are other similar restrictions as well. For example you can't have extensions defined in nested classes.
For my understanding this is a conceptual move.
The static class acts like a pure container for methods and itself does not represents the object, and the extension method by itself is the method that only processes the input and does not acts like a part of the objects behavior.
That is why I think they are very similar by its nature in the C# and probably that is why they where linked together by the language.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extension Methods vs Static Utility Class
I am building an API of general functions which perform actions based upon objects in .NET. For example; I have created a function that checks a string to see if it is an email address.
I could either have:
static bool IsEmailAddress(string text)
{
return IsMail(text);
}
or I could create an extension method that would be used like so:
string text = "HelloWorld#Email.com";
if (text.IsEmailAddress())
{
}
which is more suitable, or do you think since this is a general purpose library, I could technically implement it both ways and allow the developer to decide which is best for them?
Creating an extension method means that it will automatically show up during intellisense when a user uses that type. You have to be carefull not adding a lot of noise to the list of methods developers browse (especially when creating a reusable framework). For instance, when those methods are just usable in a certain context, you are probably better of using 'normal' static methods. Especially when implementing extension methods for general types such as string.
Take for instance an ToXml(this string) extension method, or an ToInt(this string) extension methods. Although it seems pretty convenient to have these extension methods, converting text to XML is not something you will do throughout the application and it would be as easy to have do XmlHelper.ToXml(someString).
There is only one thing worse, and that is adding an extension method on object.
If you're writing an reusable framework, the book Framework-Design-Guidelines by Krzysztof Cwalina is an absolute must read.
I prefer Extension Method, because your code is elegant, and you can define an extension method on a sealed class of the framework.
The question is which .NET Framework will you target? If < 3.5 then extension methods are not available. Otherwise, why would you create a new class?
An extension method is automatically part of a static class. This means that the consumer can use either the extension methods or call the static method from the class if she wants it. I use extension methods as much as I can, they are easier to discover if they're put in the proper namespace.
Extension methods allow developers to not be aware exactly what the helper class is called and where it is located, not to mention the very fact of its existence. Do note, that you still need to put their namespace in using clause - perhaps place them in some common, top-level namespace for your application.
I have recently started to make useful use of C# extension methods. The SO examples and the documentation suggest that they are only used for instance methods (i.e. with the this keyword). It is possible to use them (or another approach) with static/class methods?
(My particular requirement is converting Java code to C# where "most of the code" does not need editing. The Java instance methods (e.g. Java String.indexOf()) can be routed through an extension method calling C# string.IndexOf()). I would like to do the same for, say, Java Math.abs() => C# Math.Abs()).
SUMMARY No. The answers suggest it would be a reasonable thing to have but it's unlikely to happen soon. Workarounds will require editing creating new classes or something similar and may not be worth it.
You cannot create static extension methods - it's also something I've wished to be able to do!
You could create your own static classes with a standard suffix, i.e. MathJSyntax.abs(..) which would call Math.Abs(..)
C# 3.0 does not allow the creation of static extension methods, unfortunately. F# however does allow this, along with the much desired feature of extension properties.
The notation itself doesn't let you do it, the "this" class parameter expects an instance to the class to be passed in. If they intended to at least eventually add it, they wouldn't have written it like that.
So the short answer is nope, and never will be!
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.