Create extensions methods to improve C# readability

Pierre Belin
Pierre Belin
Create extensions methods to improve C# readability
Photo by name_ gravity / Unsplash
Table of Contents
Table of Contents

Methods extensions helps developers to hardly improve C# readability.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

I prefer functional zero in object classes. It is very important to separate object declarations from methods to avoid confusion and to simplify object sharing between projects.

Let's take a clear exemple: a Goat can have a list of skills. Depending on the amount of skills, a level can be determinated.

public class Goat
{
    public List<string> Skills { get; set; } = new List<string>();
}

public enum GoatLevel {
    Junior,
    Senior,
    God
}

2 methods are needed :

  • one to add a skill in order to avoid duplicated skills
  • one to determinated the level.

Therefore it is not allowed to add AddGoatSkill and GetGoatLevel inside the Goat class.

To be able to use these methods, we create a static GoatUtils and static methods.

public static GoatUtils 
{
    public static void AddGoatSkill(Goat goat, string skill)
    {
        // We do not want to add twice a skill
        if(!goat.Skills.Contains(skill)) {
            goat.Skills.Add(skill);
        }
    }

    public static GoatLevel GetGoatLevel(Goat goat) {
        switch(goat.Skills.Count()) {
            case > 9:
                return GoatLevel.God;
            case > 5:
                return GoatLevel.Senior;
            case > 0:
                return GoatLevel.Junior;       
        }
    }
}

You see what we have here. To make the method name explicit, we need to specify that the skill addition is on Goat, same for the current level.

public void Main() {
    var goat = new Goat();
    GoatUtils.AddGoatSkill(goat, "dotnet");
    var level = GoatUtils.GetGoatLevel(goat);
}

Transform methods to extensions

To convert a classical method into an extension, you must validate the following rules:

  • The class that contains the extension must be static.
  • The extension must also be static.
  • The first parameter must start with the keyword this.
public static class GoatExtensions() 
{
	public static void AddSkill(this Goat goat, string skill)
    {
        // Same content than AddGoatSkill
    }

    public static GoatLevel CurrentLevel(this Goat goat) {
        // Same content than GoatCurrentLevel
    }
}

As you can see, the content of the method has not changed, only its statement.

This is where you say, "What has really changed in the use of the two methods?"

Since the methods contain this, this means that the first parameter is passed from the object that calls the method.

In our case: GoatUtils.AddGoatSkill(goat, "dotnet") becomes goat.AddSkill("dotnet").

The first parameter of the classic method becomes the object that owns the method. The extension specifies that the object must be a type of Goat. Now all Goat objects can call this method.

The main function now looks like:

public void Main() {
    var goat = new Goat();
    goat.AddSkill("dotnet");
    var level = goat.CurrentLevel();
}

You no longer need to call an external static class that adds verbosity to your code. The AddSkill extension method appears to be part of the Goat class, although you have not modified the DTO.

Also, your IDE's autocomplete will automatically offer this extension method when you manipulate Goat objects. It is easier to use the methods offered than to remember which class contains all the Goat utilities.

Advantages & cons

Advantages:

  • Allows you to add new methods to an existing class without changing the source code (useful for autogenerated classes).
  • Keep the writing clean and simple
  • Separate DTO from logical classes (really important)

Cons:

  • I really don't see any disadvantages

Personally, I use extension methods as much as possible, especially when I code a contract that forbids me to modify DTO classes (they are mostly autogenerated).

Have a goat day 🐐



Join the conversation.

Great! Check your inbox and click the link
Great! Next, complete checkout for full access to Goat Review
Welcome back! You've successfully signed in
You've successfully subscribed to Goat Review
Success! Your account is fully activated, you now have access to all content
Success! Your billing info has been updated
Your billing was not updated