Implementing an interface
suggest changeAn interface is used to enforce the presence of a method in any class that ‘implements’ it. An interface can also require properties, events, and indexers. 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.
class Name : 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents