C# Extension Methods


         Extension methods enables you to add methods to existing type , without event creating the derived type or modifying the existing type.

 Extension methods are static methods, but they are called as if they were instance methods on the extended type.


Example Program for Extension Methods in C#

using System;

using System.Collections.Generic;

 

//Example for Extension method in C#

namespace ProgramCall

{

    class MyClass

    {

        static void Main()

        {

            string str = "This is C# 3.0";

            //Calling an Extension method , similar to an instance method

            int wordcount = str.WordCount();

            Console.WriteLine(wordcount);

 

            bool StringsEqual = str.StringCompare("Sample string");

            Console.WriteLine(StringsEqual);

            Console.ReadLine();

        }

    }

 

 

    public static class MyExtended

    {

        //Extension methods for string class

        public static int WordCount(this string s)

        {

            return s.Split(' ').Length;

        }

 

        public static bool StringCompare(this string s, string comparestring)

        {

            return (s == comparestring);

        }

    }

}

 

//Output

//4

//False


Note:
  • 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 a using directive.
  • You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.



extension methods c#.net, .net extension methods