• Sun. Oct 6th, 2024

How to use extension methods in C#

Byadmin

Oct 3, 2024



public static class MyListExtensions
{
    public static T GetLastElement(this List list)
    {
        if(list.Count > 0)
            return list[list.Count – 1];
        return default(T);
    }
}

The GetLastElement is an extension method that returns the last element of a list. You can invoke this extension method using the following code snippet.

List integers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int element = integers.GetLastElement();
Console.WriteLine(element);

Overloading an extension method in C#

Similar to other methods, you can also overload an extension method. The following code snippet shows how you can overload the Substring method of the string class to return a substring of a string. This overloaded Substring method takes the starting and ending index and a Boolean as parameters. The Boolean denotes if the returned string should be converted to upper case. If you pass true in this parameter when calling the extension method, the returned string will be converted to upper case.



Source link