So I am still very new to C# and using interfaces, and when I thought I understood them I realized I don’t completely. The confusion I have found that I am seeking some clarification here for is, when you create an interface, and have a class inherit from it
public Interface ISomeInterface
{
//some methods/properties
}
public class FooClass : ISomeInterface
{
//implemented ISomeInterfaces methods/properties
}
And you use this class object in an implementation somewhere in your program
public class BarClass
{
private ISomeInterface _someInterface;
public BarClass(ISomeInterface someInterface)
{
_someInterface = someInterface;
}
//rest of class
}
My confusion is why do I see it setup this way. I thought that I would have instantiated a new object of type FooClass, as well as used an object of type FooClass in the constructor as such:
public class BarClass
{
private FooClass _fooClass;
public BarClass(FooClass fooClass)
{
_fooClass = fooClass;
}
//rest of class
}
What am I missing to understanding this? I didn’t think I would directly be declaring objects of an Interface?
Thanks in advance.
The idea is that
BarClassshould not be tightly coupled to a specific implementation ofISomeInterface.If you use this:
it means that the BarClass can work only with this specific FooClass implementation and nothing else. Whereas if you use:
now the
BarClassis no longer tightly coupled toFooClass. This means that the consumer of theBarClasscan now pass any implementation of the interface he wants as long as it respects the defined contract (interface). So if he wantsFooClasshe passes an instance ofFooClass, but if he is not satisfied withFooClasshe can write his own implementation and pass it to the constructor and from the point of view of theBarClassthis is absolutely transparent (it doesn’t need to be modified).The weak coupling between your classes is one of the most fundamental aspects of OOP as it allows you to easily replace one component with another without having to rewrite your entire application.