can somebody please explain what actually happens when we create an object of interface?
An analogy I like to use is that an interface is like a mask - when you create an instance of a class that implements an interface (e.g. IFoo), then treat the class as the interface then the interface is like a mask that an actor would wear - the class appears to be and acts as the interface (mask) even though there is a whole bunch of stuff under the mask (interface).
but can't really grasp the logic of Why C# allows creation of an object(instance) of interface?
The other thing to mention is that an interface is a contract - whatever methods / properties / etc are defined on the interface are guaranteed to be implemented on the class. Classes that are completely and utterly different to each other can implement the same interface - when you have an instance of each class and treat it (cast it) as the interface then the same methods can be called on each class, although the implementation (actual code) in each class can be wildly different.
Example:
The classes Car
and Human
both implement the interface IMove
, and IMove
defines the method void Move();
. They are both totally unrelated classes with no common ancestry, but if you have an instance of Car and Human, then they are both guaranteed to have the method void Move()
, although the code in that method will differ between then them as they move in totally different ways. If you then cast these different objects to the same interface (var x = (IMove) someCar
or var x = someHuman as IMove
) then you can treat the object reference identically.
Interfaces and abstract classes have some similarities - they both specify things in a contractual way (the extender or implementor has to implement specific things), and they both cannot be created directly (the difference is that abstract classes can provide some implementation whereas interfaces cannot, and interfaces can only be implemented, never inherited).
If you are wondering what happens under the hood at MSIL level then there are other far more qualified people around here who can elaborate on that.