Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to use C# extension methods to enhance a class:

  1. Create a static class that contains the extension method(s).
  2. Define the extension method(s) using the “this” keyword followed by the class name that you want to extend.
  3. Use the extension method like you would any other method of the class you are extending.

Example:

Let's say you want to enhance the String class with a new method that returns a substring starting from a specified index and up to a specified length. Here's how you can do that using extension methods:

  1. Create a static class:
public static class StringExtensions
{
    // Define the extension method here.
}
  1. Define the extension method:
public static class StringExtensions
{
    public static string SubstringFromIndex(this string str, int index, int length)
    {
        return str.Substring(index, length);
    }
}

In this example, we're defining a new method called SubstringFromIndex that takes a string (the object we want to extend), an integer representing the starting index, and an integer representing the length of the substring we want to extract from the original string.

Note how we use the “this” keyword followed by the string class name, indicating that this is an extension method that applies to instances of the String class.

  1. Use the extension method:
using System;

public class Program
{
    public static void Main(string[] args)
    {
        string str = "Hello world!";
        string sub = str.SubstringFromIndex(6, 5);
        Console.WriteLine(sub); // output: world
    }
}

In this example, we're creating a new string variable and assigning it the value “Hello world!”. Then, we're calling the SubstringFromIndex extension method we defined earlier, passing in the starting index (6) and the length (5).

The extension method returns the substring “world”, which we then print to the console.

That's it! By following these steps, you can use extension methods to enhance any class in C#.