I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
I just want to know the following :
Well, first case that comes to my mind - when you don't own source code of StandAlone
class, but later you decided to introduce interface which describes behavior of StandAlone
class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone
behavior in some cases. So either you have no options for unit-testing such code:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
But if you'll introduce interface, you can actually switch to dependency from IMyInterface
instead of StandAlone
. And provide SubClass
as implementation of interface with zero efforts.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
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