An interface in C# defines a contract that classes can implement. It only contains method declarations (no implementation). A class that implements an interface must provide an implementation for all its members.
interface IVehicle
{
void Start();
void Stop();
}
class Car : IVehicle
{
public void Start()
{
Console.WriteLine("Car started.");
}
public void Stop()
{
Console.WriteLine("Car stopped.");
}
}
class Program
{
static void Main()
{
IVehicle myCar = new Car();
myCar.Start(); // Output: Car started.
myCar.Stop(); // Output: Car stopped.
}
}
interface IAnimal
{
void Eat();
}
interface IPet
{
void Play();
}
class Dog : IAnimal, IPet
{
public void Eat()
{
Console.WriteLine("Dog is eating.");
}
public void Play()
{
Console.WriteLine("Dog is playing.");
}
}
Feature | Interface | Abstract Class |
---|---|---|
Implementation | Only declarations | Can have both declarations and definitions |
Multiple inheritance | Allowed | Not allowed |
Access modifiers | Not allowed | Allowed |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!