Extension method in C#

Wesley Jesus
1 min readMar 23, 2023

--

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:

https://www.programiz.com/csharp-programming/online-compiler/

With this function, we can add new methods in our code without need of change the original class.

--

--

Wesley Jesus
Wesley Jesus

Written by Wesley Jesus

Hi, i'm a parent, developer and sometimes play soccer. I have most of 10 years of experience like programmer and is currently, i'm my prepare to master degree.

Responses (2)