Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects from an interface in C#

Tags:

c#

.net

It is possible, given only an interface, to create an object from this?

Something like:

var obj = new IWidget();

(I know this code isn't right - VS stays cannot create an instance of IWidget)

I'm in a context where my project has references to the interfaces, and I want to create concrete objects and return them from a method - but I can't figure out how to create the objects purely from the interfaces.

like image 265
wows Avatar asked Feb 02 '10 19:02

wows


People also ask

Can you create objects from interfaces?

Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the "implement" class.

Can you cast an interface to an object?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

How can we create object for an interface in C#?

You can't create an object of an interface, but you can create an object of a class and let the class use the interface.

Is it possible to instantiate objects directly from an interface?

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.


2 Answers

You can't create an object from an interface. You can create an object from a class that uses that interface.

For example:

IList<string> x = new IList<string>();

will not work.

IList<string> x = new List<string>();

will.

Interfaces cannot be created, only objects that use the interface can be created.

like image 72
taylonr Avatar answered Sep 24 '22 23:09

taylonr


That code is actually correct for COM objects, due to compiler wizardry. Normally it's not though.

The problem is, how is the compiler meant to know which implementation to create? There could be any number around. You might want to consider having a factory for the interface, or possibly using dependency injection (e.g. with Spring.NET or Castle Windsor).

like image 23
Jon Skeet Avatar answered Sep 25 '22 23:09

Jon Skeet