08 Feb 2024




Intermediate

Extension methods in C# allow you to add new methods to existing types without modifying, deriving, or recompiling the original type. They were introduced in C# 3.0 as a feature to enhance the language's expressiveness and flexibility.

Here are some key points about extension methods:

  1. Syntax: Extension methods are defined as static methods in static classes. They use the this keyword as the first parameter of the method, specifying the type to which the method applies. The this parameter indicates that the method is an extension method for instances of the specified type.

  2. Usage: Extension methods enable you to call custom methods as if they were instance methods of the extended type, providing syntactic sugar for method invocation. This means you can use dot notation to call the extension method on instances of the extended type.

  3. Namespace: To use extension methods, you need to import the namespace containing the static class that defines the extension methods.

Here's a simple example of an extension method:

using System;

public static class StringExtensions
{
    public static string ReverseString(this string input)
    {
        char[] chars = input.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string original = "hello";
        string reversed = original.ReverseString();
        Console.WriteLine(reversed); // Output: olleh
    }
}

In this example:

  • StringExtensions is a static class that contains the extension method ReverseString.
  • The ReverseString method takes a string as its first parameter (prefixed with this), allowing you to call it directly on instances of the string class.
  • In the Main method, the ReverseString method is invoked on the original string instance, even though ReverseString is not a member of the string class itself.

Extension methods are a powerful feature in C# that enables you to extend the functionality of existing types and improve code readability and maintainability.

c-sharp
extension-methods