tags:

views:

197

answers:

4

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

+2  A: 

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.

Mehrdad Afshari
Not just a class, but very importantly an *interface*.
Jon Skeet
Thanks Jon, I changed it to type to be more accurate.
Mehrdad Afshari
+9  A: 

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

JTA
A: 

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

AnthonyWJones
+1  A: 

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

David Arno
Extension methods are so much more...I can add methods to any object, but the methods have no access to private state. I don't need the source code so I can add methods to framework classes
JoshBerke