C# – Should Extension Methods of an Interface Be in the Interface.cs File?

cextension-methodinterfaces

Imagine this set up:

public interface IMass{
    double Mass {get;}
}

public static class IMassExtension {
    public static double ToKg(this IMass massObject) {
        return massObject.Mass / 1000.0;
    }

    public static double CalculateInteractiveGravity(this IMass massObject, IMass otherMassObject)          
    {
         return blah;
    }
}

Is it ok to put the extension class in the same file as the interface (i.e. IMass.cs) or should it be in a separate file (IMassExtension.cs)?


A base class is not possible here. Imagine

public class Person : Animal, IMass {}

and

public class House : Building, IMass {}

Best Answer

Yeah, that's totally fine. Further, I would encourage you to do that, as it makes the functionality available in the interface more discoverable, while reducing the noise in the "what functionality is in this csproj?" view in visual studio.

The only arguments I've heard against this are:

  • "but then you have 2 types per file!" - guidelines are there to help you, not tie your hands. You'd make it only one type if you could.
  • "but that extension uses XYZ!" - yeah, if you wouldn't include the method if it were an abstract class, then you shouldn't hard-wire it to the interface either. That's not a problem with this practice, but with your design.