Extension method in C#
Sometimes we created some static class with utilities method that help us a resolve simple problem, like format a text, convert a class and anything.
So, the C# in version 3.0 throw the extension method, that is a syntax sugar to ours utilities class.
We have the simple static class of example that create the tag label from value string.
public static class HtmlUtilities
{
public static string TransformALabelTag(string value)
{
return $"<label for="User">{value}</label>";
}
}
So, as we use this method, stay would look like this.
using System;
public class ExtensionMethodsSample
{
public static void Main(string[] args)
{
Console.WriteLine (HtmlUtilities.TransformALabelTag("arroz"));
}
}
That’s what the extension method helps us with. We can call the extension in any string value. To this, we need to add the word “this” before of parameter type of method. Example:
public static class HtmlUtilities
{
public static string TransformALabelTag(this string value) // <--- here
{
return $"<label for=\"{value}\">{value}</label>";
}
}
Now we can call the method “TransformALabelTag()” from any string. Look as stay
public class ExtensionMethodsSample
{
public static void Main(string[] args)
{
Console.WriteLine ("bestLanguageIsCshap".TransformALabelTag());
}
}
The Result:
With this function, we can add new methods in our code without need of change the original class.