.Net C# Development

Extension Methods

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 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. You 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.

OrderBy Example

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this isn’t a requirement for extension methods. For more information, see Lambda Expressions.

 static void Main()
    {
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }
    }

Benefits 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.

Leave a Reply

Your email address will not be published. Required fields are marked *