1 | initial version |
Here are the steps to use C# extension methods to enhance a class:
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:
public static class StringExtensions
{
// Define the extension method here.
}
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.
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#.