Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface instantiation vs class instantiation

Tags:

c#

interface

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.

like image 643
Nil Pun Avatar asked Aug 26 '11 23:08

Nil Pun


People also ask

What is interface instantiation?

An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Can I instantiate class in an interface?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.

Do interfaces need to be instantiated?

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class.


1 Answers

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 container is something that implements IUnityContainer, which might have an API different from UnityContainer.


Consider:

interface IAnimal  {     void die(); }  class Cat : IAnimal  {     void die() { ... }     void meow() { ... } } 

Now :

IAnimal anAnimal = new Cat(); Cat aCat= new Cat(); 

C# knows for sure anAnimal.die() works, because die() is defined in IAnimal. But it won't let you do anAnimal.meow() even though it's a Cat, whereas aCat can invoke both methods.

When you use the interface as your type you are, in a way, losing information.

However, if you had another class Dog that also implements IAnimal, your anAnimal could reference a Dog instance as well. That's the power of an interface; you can give them any class that implements it.

like image 180
NullUserException Avatar answered Oct 08 '22 12:10

NullUserException