What are Extension Methods? RRS feed




    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.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(",");


    The output is


    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.


    Tuesday, April 7, 2009 9:23 AM