What are Extension Methods?
Locked
-
Tuesday, April 07, 2009 9:22 AM
What are Extension Methods?
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
All Replies
-
Tuesday, April 07, 2009 9:23 AM
An extension method is a special kind of static method that can be associated with a type, so that it can be called as if it were an instance method of the type. This feature enables you to, in effect, “add” new methods to existing types without a new derived type, recompiling, or otherwise modifying the original type.
Extension methods are defined as static methods within a static class. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with the ”using” directive or if defined directly in the source code.
Let’s look at an example on how to define and use extension methods.
Here is an extension method Concatenate which operates on a string array. It is defined in the static class Extensions in the namespacezMyStuff.
namespace MyStuff { public static class Extensions { public static string Concatenate(this IEnumerable<string> strings, string separator) { StringBuilder sb = new StringBuilder(); foreach (string item in strings) { sb.Append(item); sb.Append(separator); } sb.Remove(sb.Length - 1, 1); return sb.ToString(); } } }
If you want to use this method on a string array, you need to bring the extension method in scope with the ”using” directive.
namespace TestExtensionMethod { using MyStuff; class Program { static void Main(string[] args) { string[] names = new string[] { "A", "B", "C" }; string s = names.Concatenate(","); Console.WriteLine(s); } } }
The output is
A,B,C
If we look at the extension method call
string s = names.Concatenate(",");<br/>
it is actually equivalent to the following call.
string s = Extensions.Concatenate(names, ",");
For additional information, please see Extension Methods (C# Programming Guide).
For more FAQ about Visual C# General, please see Visual C# General FAQ
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- Marked As Answer by Xiaoyun Li – MSFT Tuesday, April 07, 2009 9:28 AM
- Unmarked As Answer by Xiaoyun Li – MSFT Tuesday, April 07, 2009 1:45 PM
- Marked As Answer by Xiaoyun Li – MSFT Tuesday, April 07, 2009 1:46 PM

