I am new to interfaces in C#. So can somebody please explain what actually happens when we create an object of interface?
I know why we have interfaces in other languages but can't really grasp the logic of Why C# allows creation of an object(instance) of interface? If interfaces do not have function definitions or variables then how can an object be created?
I have been searching on forums but couldn't get the point. here is a tutorial i found on interfaces http://www.c-sharpcorner.com/uploadfile/6897bc/interfaces-in-C-Sharp/ if you visit the link you can see that first the writer makes object of a class and than an object of inteface. When he writes
Interface_object = class_object;
interface object extracts the features from class object...
How and why does it happen if there is no implementation and variable in the interface ?
Actually you cannot create an instance of an interface.
You create an instance of some class, implementing the interface. Actually there can be dozens of classes, implementing one interface. So when you use a variable of interface type, the only thing you are guaranteed is that the object, which is in fact referenced by the variable, implements the interface and you can use any of the interface methods, properties, etc.
interface IFoo
{
void DoFoo();
}
class Foo1: IFoo
{
public DoFoo()
{
//one implementation
}
}
class Foo2: IFoo
{
public DoFoo()
{
//the other implementation
}
}
IFoo tmp = new Foo1();
tmp = new Foo2();
You may see a deep explanation in SO: Using Interface variables
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