Guide to Implementing Interfaces in C#
Q: How do you implement interface in C# and what is its purpose?
- C#
- Mid level question
Explore all the latest C# interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create C# interview for FREE!
An interface in C# defines a contract that a class can
implement, specifying a set of properties, methods, and events that the class
must define. The purpose of an interface is to define a common set of behavior
that multiple classes can share, without requiring them to have a common base
class. In C#, you implement an interface using the : symbol followed by
the name of the interface. Here's an example:
interface IAnimal { void Speak(); } class Dog : IAnimal { public void Speak() { Console.WriteLine("I am a dog."); } }
In this example, the IAnimal interface defines a
single method called Speak. The Dog class implements this
interface using the : symbol. The Dog class must provide an
implementation of the Speak method defined by the interface, allowing it
to share common behavior with other classes that implement the IAnimal
interface.
Interfaces can also define properties and events, as well as
methods with different signatures. Here's an example that demonstrates these
features:
interface IAnimal { string Name { get; set; } void Speak(); event EventHandler Fed; } class Dog : IAnimal { public string Name { get; set; } public void Speak() { Console.WriteLine("I am a dog."); } public event EventHandler Fed; }
In this example, the IAnimal interface defines a
property called Name with a getter and setter, a method called Speak,
and an event called Fed of type EventHandler. The Dog
class implements this interface and provides its own implementation of the Speak
method, as well as a property and an event.
The main advantage of using interfaces is that they allow
you to write code that is more flexible and reusable. You can create classes
that implement multiple interfaces, allowing them to share common behavior with
a variety of other classes. You can also create methods and classes that accept
interfaces as parameters, allowing them to work with a variety of different
objects that share a common contract. This makes it easier to write code that is
adaptable to changing requirements and can be reused in a variety of contexts.


