I’m still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don’t understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don’t understand how IMyInterface can be used like a class…for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface – you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
And now you have:
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
EDIT
This addresses what I think your intended question is – Why would you declare a variable to be of an interface type?
That is, why use:
in preference to:
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this: