Extension Method in C#

Extension methods are introduced in .Net framework 3.0 that add or extend methods to existing types without creating a new derived type, recompiling, or modifying the original type. In one project, one Java developer asked me about a piece of code of C# when I saw that it was code related to Extension methods. I realize this useful feature is only for .Net, such as C# and .Net Visual Basic, but not Java (for Java, which had a similar concept but with a little bit more implementation). This article will review this topic, although it is a piece of legacy technology.

A: Introduction

The contents of this article.

  • A: Introduction
  • B: What Extension Method
  • C: How: to Implement Extension Method
  • D: How to Call an Extension Method
  • E: Example
  • F: Explanation

B: What Extension Method

Extension methods enable us to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F#, and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable<T> appears to have instance methods such as GroupByOrderByAverage, and so on. We can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable<T> type, such as List<T> or Array.

C: How to Implement Extension Method

  1. Define a static class to contain the extension method.

    The class must be visible to the client code. For more information about accessibility rules, 

  2. Implement the extension method as a static method with at least the same visibility as the containing class.

  3. The first parameter of the method specifies the type that the method operates on; it must be preceded by this modifier.

D: How to Call an Extension Method

  1. In the client calling code, add a using directive to specify the namespace that contains the extension method class.
  2. Call the methods as if they were instance methods on the type.

E: Example

The following example implements an extension method named WordCount in the CustomExtensions.StringExtension class. The method operates on the String class, which is specified as the first method parameter. The CustomExtensions namespace is imported into the application namespace, and the method is called inside the Main method.

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    // Extension methods must be defined in a static class.
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this string str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    // Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            // Call the method as if it were an
            // instance method on the type. Note that the first
            // parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

F: Explanation

Let us discuss this concept with the help of an example. Suppose you have a class or a structure that contains three methods, and you want to add two new methods to this class or structure. If you do not have the source code of the class/structure or do not have permissions from the class/structure, or the class is a sealed class, but you still want to add new methods in it, then you can use the concept extension method to add the new method in the existing class/structure. Now you create a new class which is static and contains the two methods that you want to add to the existing class, now, bind this class with the existing class. After binding, you will see the existing class can access the two newly added methods. As shown in the below program.

from

References


Similar Articles