Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
Josh Russo Avatar asked Aug 05 '11 14:08

Josh Russo


People also ask

What is the main purpose of an extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Why do extension methods need to be in a static class?

It is compulsion that the Extension method must be in a Static class only so that only one Instance is created. For example, if you place the following in ASP.Net page it will not work. Though error will not come, but you will not see the method available. The above will not work.

Are extension methods good practice?

For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.

Can we define extension method for a class which itself?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.


1 Answers

There are a number of reason Microsoft did this. The two biggest being:

  1. 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.

  2. 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.

like image 104
Michael Edenfield Avatar answered Oct 10 '22 19:10

Michael Edenfield