I'll try to explain this more conceptually.
but why we can write Interface on left side?
We can, because it means: "this object is something that implements this interface".
Interface by itself is not "something" - that's why you can't instantiate it directly - it's only a contract.
An interface is useless unless you define some object that is guaranteed to implement the contract expressed by it (and expose such and such methods etc.). That's the use you make of interfaces. Without this, they'd make no sense.
The contract itself is an abstract concept. It needs something to embody it - an object that fullfills it.
Have a look at the following example:
using System.Collections.Generic;
namespace App
{
class Program
{
class Example
{
List<string> list = new List<string> { "a", "b", "c" };
public IEnumerable<string> AsEnumerable()
{
return list;
}
}
static void Main(string[] args)
{
IEnumerable<string> foo = new Example().AsEnumerable();
List<string> bar = (List<string>)foo;
}
}
}
You know it doesn't crash?
IEnumerable<string>
in this line:
IEnumerable<string> foo = new Example().AsEnumerable();
actually means: "foo is something that we know to implement IEnumerable".
But it is still that something. It can't be only IEnumerable and nothing but. IEnumerable is just something that we happen to know about this something.
Otherwise we couldn't cast it back to List<string>
, could we? (This is actually a common caveat in C#, because the caller could do this cast, therefore gaining access to Add
and Remove
methods and messing with the contents of our list even though we intended them not to. It's encapsulation leakage).
In other words: IEnumerable<string>
is the way we look at this object.
EDIT:
As @Kjartan suggested, you could verify this all like so:
bool isFooIEnumerable = foo is IEnumerable<string>; // it's true
bool isBarIEnumerable = bar is IEnumerable<string>; // true again
bool isFooList = foo is List<string>; // yup. true
bool isBarList = bar is List<string>; // true all the way