Search⌘ K
AI Features

Implementing Interfaces

Explore how to implement interfaces in C# to define common capabilities across unrelated classes. This lesson guides you through creating and using interfaces to control devices such as electric cars and TVs, highlighting the difference between interfaces and abstract classes. You will gain practical skills in enforcing behavior contracts for maintainable, flexible code design.

We will examine interfaces in action by writing code. We have the ElectricCar class that simulates an electric car.

C# 14.0
namespace Interfaces;
public class ElectricCar
{
public bool CarOn { get; private set; }
public void StartTheCar(int keyId)
{
if (KeyValid(keyId))
{
CarOn = true;
Console.WriteLine("Starting the car.");
}
else
{
Console.WriteLine("Where are your keys?");
}
}
public void TurnTheCarOff()
{
CarOn = false;
Console.WriteLine("Car off.");
}
public void Drive()
{
if (CarOn)
{
Console.WriteLine("Car driving.");
}
else
{
Console.WriteLine("First, you have to start the car.");
}
}
private bool KeyValid(int keyId)
{
// Simple validation check
return keyId == 14;
}
}
  • Line 1: We use a file-scoped namespace.

  • Line 5: We define a property CarOn with a private setter to protect the state.

  • Lines 7–18: We define the StartTheCar method to enable the car if the key is valid.

  • Lines 20–24: We define the TurnTheCarOff method to update the car’s state to off and prints a notification message.

  • Lines 26–36: We define the Drive method to check the car’s state and allows driving only if the car is currently running.

  • Lines 38–42: We define the KeyValid private method to verify if the key ID matches the required value. We simplify the validation logic to return the result of the comparison directly.

Now, let’s look at how we run this code.

C# 14.0
using Interfaces;
var car = new ElectricCar();
Console.WriteLine("We've got a Tesla.");
Console.WriteLine("Attempting to drive it.");
car.Drive(); // Fails because car is off
car.StartTheCar(15); // Fails (wrong key)
car.StartTheCar(14); // Success
car.Drive(); // Success
car.TurnTheCarOff();
  • Line 3: We instantiate the ElectricCar. ...