techmore.in

C# - Interface

In C#, an interface defines a contract that a class or struct must follow. It contains method and property declarations, but no implementation. Classes or structs that implement the interface must provide the actual implementations of its members.

Key Features of Interfaces:

  1. No implementation: An interface contains only declarations, not the actual method or property implementation.
  2. Multiple inheritance: A class or struct can implement multiple interfaces, which is useful when you need to inherit behavior from multiple sources.
  3. Cannot contain fields: Interfaces cannot contain fields, constructors, or destructors.
  4. Public by default: Members of an interface are always public, and you cannot include access modifiers.

Syntax:

csharp
public interface IAnimal { void MakeSound(); // Declaration of method void Sleep(); // Declaration of another method }

Implementing an Interface:

A class that implements an interface must provide implementations for all members declared in the interface.

csharp
public class Dog : IAnimal { public void MakeSound() // Provide implementation for interface method { Console.WriteLine("Woof!"); } public void Sleep() // Provide implementation for interface method { Console.WriteLine("Sleeping..."); } }

Multiple Interface Inheritance:

A class can implement more than one interface.

csharp
public interface IAnimal { void MakeSound(); } public interface IMovable { void Move(); } public class Cat : IAnimal, IMovable { public void MakeSound() { Console.WriteLine("Meow!"); } public void Move() { Console.WriteLine("Cat is moving"); } }

Usage:

You can work with interfaces polymorphically. That is, you can reference objects of different classes that implement the same interface via the interface type.

csharp
IAnimal animal = new Dog(); animal.MakeSound(); // Output: Woof! animal = new Cat(); animal.MakeSound(); // Output: Meow!

Key Points:

  • Interface vs. Abstract Class: Interfaces are purely contracts without any implementation. In contrast, abstract classes can have both declared and implemented methods.
  • Multiple Inheritance: A class can implement multiple interfaces, but it can only inherit from one class (abstract or concrete).
  • Default Methods (since C# 8.0): Starting in C# 8.0, interfaces can have default implementations, but this feature should be used with care.