What are extension methods in .NET?
EDIT: I have posted a follow up question at Usage of Extension Methods
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Reference: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx
Here is a sample of an Extension Method (notice the
thiskeyword infront of the first parameter):Now, the above method can be called directly from any string, like such:
The added methods will then also appear in IntelliSense:
(source: scottgu.com)
As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.
Take a look at the following example:
As you see, the class
Extendingis adding a method named average to classExtended. To get the average, you callaveragemethod, as it belongs toextendedclass:Reference: http://aspguy.wordpress.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/