Curriculum
In C#, an interface is a reference type that defines a set of members (methods, properties, events, and indexers) that implementing classes must provide implementations for. An interface is similar to an abstract class in that it provides a contract for its implementing classes, but it differs from an abstract class in that it cannot provide any implementation for its members.
Here’s an example of an interface in C#:
public interface IAnimal { void MakeSound(); } public class Cat : IAnimal { public void MakeSound() { Console.WriteLine("Meow!"); } } public class Dog : IAnimal { public void MakeSound() { Console.WriteLine("Woof!"); } }
In this example, we have an interface IAnimal
with a single method MakeSound()
. The Cat
and Dog
classes implement the IAnimal
interface, which means they must provide an implementation for the MakeSound()
method.
Here are some rules to keep in mind when using interfaces in C#:
interface
keyword.In summary, interfaces in C# provide a way to define a contract that must be fulfilled by any class or struct that implements the interface. This allows for a more flexible and extensible design of object-oriented programs, and enables polymorphism by allowing objects of different types to be treated as instances of the same interface.