Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when we create an object of interface? [duplicate]

Tags:

c#

oop

interface

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 ?

like image 250
B-Abbasi Avatar asked Jun 25 '13 06:06

B-Abbasi


1 Answers

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

like image 167
horgh Avatar answered Oct 19 '22 04:10

horgh