Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do you mean by "extension methods" in C#?

Tags:

c#

Can anyone else explain this, (beginners approach). Thanks..

like image 866
yonan2236 Avatar asked Jan 21 '23 14:01

yonan2236


1 Answers

Extension Methods are just static methods in static classes that behaves like they were defined in other class.
In the first parameter before the type goes the keyword this wich indicates that is an extension method.

Example:

public static class Extensions
{
    public static object ExtensionMethodForStrings( this string s, object otherParameter)
    {
        //....
        return //whatever you want to return or not
    }
}

This is an extension method on System.String that takes two parameters: - string s : This is the instance variable - object otherParameter: You can have as many as you want including none

You can call this method in two ways:

Static way:

string s = "Your string";
object o = new object(); // or whatever you want
object result = Extensions.ExtensionMethodForStrings(s,o);

Extension Method way

string s = "Your string";
object o = new object(); // or whatever you want
object result = s.ExtensionMethodForStrings(o);

In the second case it works as if the type string has an instance method called ExtensionMethodForStrings. Actually for the compiler the are equivalent.

like image 120
Carlos Muñoz Avatar answered Feb 02 '23 19:02

Carlos Muñoz