Extension Methods2 min read

What are extension methods and how do you write them?

Let’s dive together into extension methods world and make our future code more productive and easier to read and maintain.

DEFINITION OF EXTENSION METHOD

Extension methods are nothing else but methods which we write to extend or add additional functionalities to an existing class and all of that without changing it’s source code or creating a new class which inherits from it.

They are static methods which MUST start with this  keyword as a first parameter, to know which type we are extending.

So let’s see how to write extension methods and how to use them!

EXTENSION METHOD IN ACTION


static void Main(args) {

    string someText = "Some super duper cool text which needs to get shortened!";

    var shortenedText= someText.Shorten(3);

    Console.log(shortenedText);

    // output:  "Some super duper"

}


public static class ExtensionExamples {

    public static string Shorten(this string textToShorten, int numberOfWords){

        if (numberOfWords <= 0 ) {

            return "";

        }

        var words = textToShorten.Split(' ');

        if (words.Length <= numberOfWords) {

            return textToShorten

        }

        return textToShorten.Join(" ",textToShorten.Take(numberOfWords));

    }

}

SUMMARY

  • They are custom methods which extend original functionalities
  • They can be added to any interfaces, struct or 3rd party classes
  • MUST be static type
  • Unlike static method, extension method MUST have this keyword as a first parameter to define a type which will be extended
  • They can be used inside application anywhere by including namespace of the extension method.

[UPDATED EXAMPLE AT 16.7.2019.]

How to display friendly names for enum in C#

If you have enum like this one:

    public enum DispatchDemandInputType
    {
        Default = 0,
        [Description("t/year")]
        TYEAR,
        [Description("m3/year")]
        M3DAY,
    }

And you want to access Description attribute easily in code (i.e. to output as a label text) like this:

product.DemandType.GetDescription(); // where DemandType is of type DispatchDemandInputType (enum)

Then all you have to do is write an extension method to make your life easier like this:

public static class EnumExtensions
{
  public static string GetDescription(this Enum value)
   {
    return value.GetType().GetField(value.ToString())?.GetCustomAttribute()?.Description;
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *