C# interface and implementation in the same file – good idea?

My recommendation is to always follow a rule of one item per .cs file, be it an enumeration declaration, interface or class. The name of the .cs file should match the name of the thing it contains.

Simple rule, easy to follow. We use StyleCop internally to police this.

If you combine this approach with a sensible use of namespaces then it should mean that your solution explorer view in Visual Studio makes it easy to navigate the components in your projects. Note that ReSharper gives an alternative approach to this navigation, but using this is not to everyone’s tastes (and not everyone might have an Add-In such as ReSharper).

Travis G has asked about finer points such as delegates and custom EventArgs declarations. Since custom EventArgs are classes, I would put them in their own files (again, keeping the rule simple). Delegates I would declare with the class that uses them. If I found I had a lot of delegates that were used in many places I might consider placing them all in a Delegates.cs file (I sometimes do this with constants, in a Consts.cs file).

However, some of this is certainly subjective and getting into the realms of software religious wars.

Leave a Comment