Home > Software engineering >  What does the extension method do in c# and why do you need it?
What does the extension method do in c# and why do you need it?

Time:04-23

I am recently learning about c# and read that the extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. What are some examples to clarify this?

CodePudding user response:

Extension Methods allow an existing type to be extended with new methods without changing the definition of the original. It allows you to add functionality to a type that you may not be able to inherit (because it's sealed) or you don't have the source code.

Here is an example. We will add an Age() method to DateTime:

public class Program
{
    public static void Main()
    {
        DateTime birthdate = new DateTime(1980, 10, 7);

        Console.WriteLine("Your age is: "   DateTime.Now.Age(birthdate));
    }   
}


public static class Extensions
{
    public static int Age(this DateTime date, DateTime birthDate)
    {
        int birthYear = birthDate.Year;
        int currentYear = DateTime.Now.Year;

        return currentYear - birthYear - 1;
    }
}

You can see from the example that we added a new Age() method to C#'s DateTime type. Hopefully this clears things up.

CodePudding user response:

Extension methods are special static methods in a static class which enables us to add new methods to built-in types and custom types without creating new derived type. Which provides a user defined custom functionality just like built-in methods have. For Example, String has ToLower(), ToUpper() methods. In same way we can create our own method.

Let's check following example, we have created Remove() method which removes any given character/string from original string.

public class Program
{
    public static void Main()
    {
        string sample1 = "This, is a, sample string";

        Console.WriteLine("output string : "   sample1.Remove(","));
    }   
}


public static class SampleExtensions
{
    public static string Remove(this string str1, string InputStr)
    {       
        return str1.Replace(InputStr,"");
    }
}
  • Related