Member-only story

Interface in C# with Example

Shahzad Aslam
3 min readApr 27, 2024

--

Multiple inheritance is not supported in C#. So for accomplishing multiple inheritance (many to many relationship) we use interface. For making interface we use interface keyword and give a interface name. Interface have method without body. A set of method, properties signatures are defined in interface that can be implement only in that class which derived from this interface. A class which implement to interface that will have methods with body.

interface in C# with Example

Declare and use Interfaces :

Here’s how you declare and use interfaces in C#

Example

public interface ITastable
{
Void Taste(); // Method signature
}
public class Mango: ITastable
{
public void Taste();
{
Console.WriteLine("Mango has sweet and creamy taste.");
}
}

In this example:

  1. We define an interface called ITastable with a single method signature Taste().

2. We create a class Mango that implements the ITastable interface. This means that the Mango class must provide an implementation for the Taste method defined in the interface.

Multiple Inheritance:

3. C# allows a class to implement multiple interfaces. This feature enables a class to inherit behavior from multiple sources, which is…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)