Can anyone else explain this, (beginners approach). Thanks..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With