c# extension methods

c# extension methods

Extension methods are static methods, which are called as if they were instance methods on the extended type. With Extension methods, you can add methods to existing types without even creating a new derived type, recompiling, or modifying the original type. You can use extension methods to extend a class or interface, but not to override them. The first parameter would be, this string str.

 

public static class StringExtensions
{
    public static string FirstLetterUpperCase(this string str)
    {
        char letter = Char.ToUpper(str[0]);
        string remaining = str.Substring(1);

        return letter + remaining;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string word = "india"
                      .FirstLetterUpperCase();

        Console.WriteLine(word);
        Console.ReadKey();
    }
}

2021-10-03