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.


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!


[syntax_prettify  linenums="linenums"]
static void Main(args) {
    string someText = "Some super duper cool text which needs to get shortened!";
    var shortenedText= someText.Shorten(3);
    // 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));


  • 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.


How to display friendly names for enum in C#

If you have enum like this one:

[syntax_prettify linenums=”linenums”]
public enum DispatchDemandInputType
Default = 0,

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

[syntax_prettify linenums=”linenums”]
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:

[syntax_prettify linenums=”linenums”]
public static class EnumExtensions
public static string GetDescription(this Enum value)
return value.GetType().GetField(value.ToString())?.GetCustomAttribute()?.Description;

(Visited 50 times, 1 visits today)

Leave a comment

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