Implementing an interface

suggest change

An interface is used to enforce the presence of a method in any class that ‘implements’ it. The interface is defined with the keyword interface and a class can ‘implement’ it by adding : InterfaceName after the class name. A class can implement multiple interfaces by separating each interface with a comma.

: InterfaceName, ISecondInterface

public interface INoiseMaker
{
    string MakeNoise();
}

public class Cat : INoiseMaker
{
    public string MakeNoise()
    {
        return "Nyan";
    }
}

public class Dog : INoiseMaker
{
    public string MakeNoise()
    {
        return "Woof";
    }
}

Because they implement INoiseMaker, both cat and dog are required to include the string MakeNoise() method and will fail to compile without it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents