articles

Home / DeveloperSection / Articles / Extension methods in C#

Extension methods in C#

Anchal Kesharwani6287 25-Jun-2014

In this article describe the concept of extension method in c#. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Here we describe the uses of extension methods and simple example of extension methods n c#.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Extension methods are defined as static methods but are called by using instance method syntax. 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.

Advantages of extension methods

·     Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.

·    If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.

·         This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

Disadvantages of extension methods

·     An extension method with the same name and signature as an instance method will not be called.

·     Extension methods cannot be used to override existing methods.

·      The concept of extension methods cannot be applied to fields, properties or events.

Syntax for creating extension methods
static class <class_name>
{
                static <return type> <method name> (this extension_class object)
{
                // definition
}
}

Here we create the extension method using the ‘this’ keyword and it refer to the

class which extension method create.

Example

using System;

 

namespace ExtensionMethods

{

   static class ExtensionMethods

    {

        public static int WordCount(this string str) // create string extenstion method for word count

        {

            return str.Split(new char[] { ' ''.''?' },StringSplitOptions.RemoveEmptyEntries).Length;

        }

     

        public static void printAll(this int[] arrayInteger) // print all item of integer array

        {

            for (int i = 0; i < arrayInteger.Length; i++)

            {

                Console.WriteLine(arrayInteger[i]);

            }

        }

        public static void print(this int[] arrayInteger, int index) // print specific item at given index

        {

            Console.Write(arrayInteger[index]);

        }

    }

}

 

namespace StringExtensionMethodsExample

{

    using ExtensionMethods;

    class Program

    {

        static void Main(string[] args)

        {

            string s="This is an program of extension methods.";

/// Here we show extension method of string class

Extension methods in C#

            Console.WriteLine("Word is counted: " + s.WordCount()); // call the WordCount method as extension method of string

            int[] arrayInt = new int[5];

            arrayInt[0] = 1;

            arrayInt[1] = 2;

            arrayInt[2] = 3;

            arrayInt[3] = 4;

            arrayInt[4] = 5;

            Console.WriteLine("Array data are printed....");

// Here we show extension methods of integer array

Extension methods in C#

            arrayInt.printAll(); // call the printAll method as extension method of string

            Console.WriteLine("---------------------");

            arrayInt.print(4); // call the print method as extension method of string

            Console.ReadKey();

          

        }

    }

} 

 

 

Extension methods in C#

In this example we are trying to understand how work the extension method in c#.


Updated 07-Sep-2019

Leave Comment

Comments

Liked By