I recently seen some C# code where the interface declaration and implementation where in the same file, like this
namespace MyNameSpace.Foo { public interface IFoo{ void DoThis(); } public class Foo : IFoo { public void DoThis(); } }
At first glance it seems all wrong to have declaration and implementation in the same file, but there are practical benefits. e.g. When you Go To Definition in Visual Studio the interface and implementation are there in the same file. This approach does not prohibit you from having other implementations of the interface, such as may be needed for unit testing. For interfaces that will only have one implementation I think this can be a pragmatic approach.
Good or bad idea?
Extending the question:
How do people use Visual Studio to navigate to an implementation when you have an interface reference IFoo myFoo = FooFactory.getFoo(MY_FOO);
If I right click on IFoo and select Go To Definition I can get the interface declaration. Is there a way for me to get the list of implementations of IFoo as that's what I'm really interested in getting to.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With