C# – Declaring Interface in the Same File as Base Class: Good Practice?

cinterfacesnetvisual studio

To be interchangable and testable, normally services with logic needs to have interface, e.g.

public class FooService: IFooService 
{ ... }

Design-wise, I agree with this, but one of the things that bothers me with this approach is that for one service you will need to declare two things (the class and the interface), and in our team, normally two files (one for the class and one for the interface). Another discomfort is the difficulty in navigation because using "Go to definition" in IDE (VS2010) will point to the interface (since other classes refer to the interface), not the actual class.

I was thinking that writing IFooService in the same file as FooService will reduce the above weirdness. After all, IFooService and FooService are very related. Is this a good practice? Is there a good reason that IFooService must be located in its own file?

Best Answer

It doesn't have to be in its own file, but your team should decide on a standard and stick to it.

Also, you're right that "Go to definition" takes you to the interface, but if you have Resharper installed, it's only one click to open a list of derived classes/interfaces from that interface, so it's not a big deal. That's why I keep the interface in a separate file.

 

Related Topic