What does the extension method do in c and why do you need it

0 votes
I'm new to c# and learned that extension methods allow you to "add" methods to existing types without having to create a new derived type, recompile, or otherwise modify the original type. What instances can you give to illustrate this?
Jun 11, 2022 in C# by jyoti
• 1,240 points
• 2,028 views

1 answer to this question.

0 votes

Extension Methods allow you to add additional methods to an existing type without affecting the original's specification. It enables you to extend the functionality of a type that you may not be able to inherit (because it is sealed) or for which you do not have the source code.

Here's an illustration. To DateTime, we'll add an Age() method:

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;
    }
}

We added a new Age() function to C#'s DateTime  type, as you can see in the example. If you need more examples, reply back to me.

answered Jun 21, 2022 by krishna
• 2,820 points

Related Questions In C#

0 votes
1 answer

What are the differences between C, C# and C++ in terms of real-world applications?

C is a bare-bones, straightforward, and clean ...READ MORE

answered May 30, 2022 in C# by rajiv
• 1,620 points
• 2,550 views
0 votes
1 answer

What is LINQ and what does it do

LINQ or Language Integrated Query may refer to: a ...READ MORE

answered Jun 21, 2022 in C# by jyoti
• 1,240 points
• 1,568 views
0 votes
0 answers

What are the differences between C, C# and C++ in terms of real-world applications?

As the title states, what are the ...READ MORE

Sep 26, 2022 in C# by krishna
• 2,820 points
• 1,262 views
0 votes
1 answer