I’m working through the Composite Application Guidance and often come across instantiation of an object of type interface e.g.:
IShell shell = new Shell();
instead of type class:
Shell shell = new Shell();
- What are the differences between these two?
- Why is the first way used at all (since the second shell object can be used anywhere an IShell interface is specified, right?)
You might want to do that if the class has an explicit implementation of an interface method. Consider this example:
If you want ISomething.Action to be called on Something, then you use have to call it through an ISomething variable. Even in Something2, the Action method is hidden if you don’t do it through the interface.
That said, you usually want to avoid having implementations like that. I doubt a framework class would force you into that, but that would be the scenario to declare it with the interface.
Update 1: To clear it up a bit, some extra code on how to get to the methods: