C# language feature:

  • Extension methods

applies to

  • objects

benefit

  • Enables “adding” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

how to use

  • 1) Declare namespace in new class file with desired name.
  • 2) Declare a public static class with desired name.
  • 3) Declare a method and precede the first parameter of class being extended with this keyword.
  • 4) Add using namespace and reference extension method on class being “extended”.
  • 5) Declare and call the extended method.

Notes

  • Extension methods must have unique method signatures not available in original type. Use extension methods sparingly. Prefer extending via inheritance.

example:

    namespace CodeSage.ExtensionMethod // 1) Declare namespace in new class file.
    {   
        // 2) Declare a `public static class` with desired name. 
        public static class Extension_Method_Example 
        {
            // 3) Declare a method and precede the first parameter of class being extended with `this` keyword.
            static public bool HasSpace(this String str)  // String is the class being extended
            {
                return !(str.IndexOf(' ') == -1);
            }
        }
    }

    // to use an extension method

    namespace CodeSage.ExtensionUse
    {
        // 4) Add using namespace and reference extension method on class being "extended".
        using CodeSage.ExtensionMethod;

        public class Use_of_Extension_Method
        {
            public void test()
            {
                String sometext = "Hi I have a space"; // 5) Declare and Call the extended method
                bool result = sometext.HasSpace(); 
            }
        }
    }