Could someone please helpme to understand if the following codes are same. If not what’s the difference between class and interfance instantiation.
IUnityContainer container = new UnityContainer()
UnityContainer container = new UnityContainer()
As far as I understand Inteface has only method signature and if the interface has been implemented by 3 classes. Not too sure which of the 3 instance would be created by first statement above.
Thankyou.
Interfaces can’t be instantiated by definition. You always instantiate a concrete class.
So in both statements your instance is actually of type
UnityContainer.The difference is for the first statement, as far as C# is concerned, your
containeris something that implementsIUnityContainer, which might have an API different fromUnityContainer.Consider:
Now :
C# knows for sure
anAnimal.die()works, becausedie()is defined inIAnimal. But it won’t let you doanAnimal.meow()even though it’s aCat, whereasaCatcan invoke both methods.When you use the interface as your type you are, in a way, losing information.
However, if you had another class
Dogthat also implementsIAnimal, youranAnimalcould reference aDoginstance as well. That’s the power of an interface; you can give them any class that implements it.