Interfaces in C#

Define CAN-DO abilities. Like USB ports - any device that fits the contract works.

60-Second Version: Interface = contract. interface IDrivable says "you MUST have Start()". No code inside. Multiple interfaces allowed.

1. Interface = Pure Contract

public interface IDrivable
{
    void Start(); // No code, no access modifier
    void Stop();
}

public class SportsCar : IDrivable
{
    public void Start() { Console.WriteLine("VROOM!"); } // Must implement
    public void Stop() { Console.WriteLine("Screech!"); } // Must implement
}

2. Multiple Interfaces = Multiple Abilities

public interface IFlyable { void Fly(); }

public class FlyingCar : IDrivable, IFlyable // Multiple OK
{
    public void Start() { }
    public void Stop() { }
    public void Fly() { Console.WriteLine("Taking off"); }
}
Beginner Trap: Interfaces can't have fields or constructors. Only methods, properties, events. Use abstract class if you need fields.

Quick Check ๐Ÿง 

Next: Encapsulation - Protect data with private fields and public properties.

Comments on Interfaces (0)

No comments yet. Be the first to share your thoughts!