I Don't understand some things about the below code, I wonder if you can help me.
What first confused me is the following explanation from Microsoft docs;
What I didn't understand is why I am assigning "myClass" to variable "myInterface" of type "IMyInterface".
Firstly, I'm surprised this is allowed, You can't assign a String to an Int variable, so why can i assign an instance of a class type to a variable of an Interface type?
Microsoft Docs mentions "an interface cannot be instantiated using the new operator", But why would you want to instantiate an interface. Isn't the design of interfaces that they are just a contract enforcing any inheriting class to implement the properties and methods that the interface contains, why would you ever need to assign a class to an interface?
I Investigated exactly the rules surrounding the Microsoft docs piece below, I realized that if you declare an interface, inherit it in another class, you can then assign the class that has inherited that interface to a variable of the interface type, then call the variable of the interface type as if it was a class ( the whydoesthiswork variable in the below code).
This hasn't helped me understand why this is possible, what the point in this confusing syntax is and why you would ever want to do this.
Any help would be appreciated, thank you.
interface IAnimal
{
void animalSound();
}
class Pig : IAnimal
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
IAnimal whydoesthiswork = new Pig();
whydoesthiswork.animalSound();
}
}
