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 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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With