An interface in C# is like a promise or contract. It tells what methods or properties a class must have, without saying how they work.
0
0
Interface as contract mental model in C Sharp (C#)
Introduction
When you want different classes to share the same set of actions but do them differently.
When you want to make sure a class follows certain rules or structure.
When you want to write code that works with many types of objects in the same way.
When you want to separate what something does from how it does it.
When you want to make your code easier to change or add new features later.
Syntax
C Sharp (C#)
interface IExample { void DoWork(); int Calculate(int value); }
Interfaces only declare methods or properties, they do not provide the code inside them.
Classes that use an interface must implement all its members.
Examples
This interface says any class that is an IAnimal must have a Speak method.
C Sharp (C#)
interface IAnimal { void Speak(); }
IVehicle requires two methods: StartEngine and StopEngine.
C Sharp (C#)
interface IVehicle { void StartEngine(); void StopEngine(); }
The Dog class promises to follow IAnimal by implementing Speak.
C Sharp (C#)
class Dog : IAnimal { public void Speak() { Console.WriteLine("Woof!"); } }
Sample Program
This program shows two classes, Teacher and Engineer, both promise to work by following the IWorker interface. Each does work differently.
C Sharp (C#)
using System; interface IWorker { void Work(); } class Teacher : IWorker { public void Work() { Console.WriteLine("Teaching students."); } } class Engineer : IWorker { public void Work() { Console.WriteLine("Building software."); } } class Program { static void Main() { IWorker worker1 = new Teacher(); IWorker worker2 = new Engineer(); worker1.Work(); worker2.Work(); } }
OutputSuccess
Important Notes
Interfaces help keep code organized and clear by defining clear rules.
You cannot create an object directly from an interface; you must use a class that implements it.
Interfaces support multiple inheritance, meaning a class can follow many interfaces.
Summary
An interface is a contract that says what methods a class must have.
It helps different classes share the same actions but with their own details.
Using interfaces makes your code flexible and easier to manage.