C#C
C#8mo ago
Faker

✅ Interface in C#

Hello, I have a question, consider the following code:

C#
// Define an interface
public interface IAnimal
{
    void Speak();
}

// Implement the interface in a class
public class Dog : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Woof!");
    }
}


C#
IAnimal myDog = new Dog();  
myDog.Speak();              // Output: Woof!


My question is, an interface is just like an abstract class in the sense that we can' instantiate directly but rather should be instantiated indirectly by using a derived class from it.

When we write:

C#
IAnimal myDog = new Dog();
myDog.Speak();             


I don't understand, we are creating a Dog object, this references a dog? What is the IAnimal data type? What does it represents and why not use Dog instead?
Was this page helpful?