C# Interfaces

What is an Interface?

An interface is a contract that defines what methods a class must have.

It does not contain full implementations (in basic usage), only method definitions. Classes that implement the interface must provide the actual logic.

Loading...
Output:

Why Use Interfaces?

Interfaces allow different classes to follow the same structure while having different implementations.

  • Promotes code flexibility
  • Supports abstraction
  • Allows multiple behaviors
  • Used heavily in real-world applications

Implementing an Interface

A class implements an interface using the : symbol.

The class must provide implementations for all interface methods.

Loading...
Output:

Using Interface References

You can use an interface as a reference type, which allows you to work with different classes in a consistent way.

The method that runs depends on the actual object type.

Loading...
Output:

Multiple Interfaces

A class in C# can implement multiple interfaces.

This allows a class to have multiple behaviors, which is not possible with inheritance alone.

Loading...
Output:

Interface vs Class

Interfaces and classes are both used in object-oriented programming, but they serve different purposes.

  • Class: contains both data and implementation
  • Interface: defines required behavior
  • Class: can only inherit one class
  • Interface: can implement multiple interfaces

Real-World Example

Interfaces are commonly used to define shared behavior across different types.

Loading...
Output:

Why Interfaces Matter

Interfaces are widely used in C# applications, especially in large systems and frameworks.

  • Used in dependency injection
  • Essential in ASP.NET applications
  • Encourages loosely coupled code

Practice

Create an interface IVehicle with a Start() method. Then create Car and Bike classes that implement it.

Loading...
Output:

Need Help?