How do interfaces work in C#?


An interface defines a contract that will be implemented by a class or a struct. It can contain methods, properties, events, and indexers. An interface is similar to a class except that it doesn't hold any data and only specifies the behavior it can do (or more accurately, the class that implements it can do).

A class can implement one or more interfaces. To implement an interface member, the class should have a public member with the same method definition as the interface member, i.e. same name and signature.

For example, IComparer is an interface defined in the System.Collections namespace that defines the contract for a method that compares two objects. The Car class implements the IComparer interface

public interface IDriver{
   void Drive();
}
public class Car : IDriver{
   public string Name { get; set; }

   public int Speed { get; set; }
   public void Drive(){
      Console.WriteLine($"{Name}: {Speed}");
   }
}

All the members on an interface are implicitly abstract and don't have any implementation details. All interface members are public. You can't use an access modifier with an interface member. The class implementing an interface must provide public methods that implement the interface.

An interface can extend other interfaces, for example −

public interface IPerformer { void Perform(); }
public interface ISinger : IPerformer{
   void Sing();
}

Interfaces allow you to include the behavior from multiple sources in a class. Since C# doesn't allow multiple inheritance like C++, interfaces are one way to achieve multiple in C#.

A drawback of interfaces is that they are less flexible than classes when you use them to expose APIs. When you change an interface's contract, all the classes that implement that interface break and need to update to implement the interface.

Example

 Live Demo

using System;
class Program{
   static void Main(){
      var carOne = new Car { Name = "Honda", Speed = 100 };
      var carTwo = new Car { Name = "Toyota", Speed = 70 };
      carOne.Drive();
      carTwo.Drive();
   }
}
public interface IDriver{
   void Drive();
}
public class Car : IDriver{
   public string Name { get; set; }
   public int Speed { get; set; }
   public void Drive(){
      Console.WriteLine($"{Name}: {Speed}");
   }
}

Output

Honda: 100
Toyota: 70

Updated on: 19-May-2021

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements