Disadvantages of using extension methods instead of instance methods in C #

Let's say I have a class named Building

. This is created at the beginning of the program. I need to do as hundreds of operations on variables of the Building class. I now have two choices.

1. Define different classes with methods and pass the building to them.

class StoryService
{
    private readonly Building building;

    public StoryService(Building building)
    {
        this.building = building;
    }

    public void AddStory() {}
}

      

2. Define extension methods for Building

static class StoryExtensionMethods
{
    public static void AddStory(this Building building) {}
}

      

Now in my application:

var building = new Building();

// Method 1
var storyService = new StoryService(building);
storyService.AddStory();


// Method 2
building.AddStory();

      

Now my question is which one is the path to performance and good practice. Which one will reduce class cohesion?

+3


source to share


1 answer


I've never found a particularly compelling reason to use static extensions, as it might (if anyone else is working on the codebase) confuse them a bit, because there are several places to look for method declarations for a given class.

That said, static extensions for things you don't have (adding a new method to the line to create its header, for example) make a lot of sense.



So I would say to avoid this if possible, but if you feel the need or are unable to edit the class itself, create an extension and make sure other people know about it.

The performance effect is negligible.

+3


source







All Articles