This question already has an answer here:
What are Extension Methods? 5 answers
Usage of Extension Methods 9 answers
What Advantages of Extension Methods have you found? [closed] 30 answers
So I run into the term “extension-methods” frequently, when reading about .Net and intellisensing (!) around…
What are extension-methods — and what sets them apart from other methods?
They’re static methods that can be added to other types without modifying the original type.
For example, say you want to be able to call ToInt() on a string. You can create a method like this:
Now say you have a TextBox called Port on your web page you can get it as an int like this:
Real world use of extension methods is usually much more useful then that and is used heavily by Fluent APIs and testing frameworks.
UPDATE: Another good use of extensions is to provide base class like default behaviors for interfaces. Many popular testing methodologies depend on interface definitions and the ability to mock those interfaces. Unfortunately, basing everything on interfaces however loses some of the benefits of inheritance. Extension methods can add some of the convenience of base classes without the pollution of the interfaces.
For example say I have a
Windowbase class defined like thisNow I want to extract an
IWindowinterface from this class. I don’t really want to require every object that derives fromIWindowto have to implement the secondShowmethod since it’s just a basic overload. So I can define my interface like this:And an extension method like this: