Interface instantiation vs class instantiation in C#

Interfaces can’t be instantiated by definition. You always instantiate a concrete class. When you use interface variables in your code, it allows you to more easily switch out the concrete implementation, which makes your code more flexible.That’s the power of an interface.

IUnityContainer container = new UnityContainer()
UnityContainer container = new UnityContainer()

So in both statements  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.


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.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s