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'll cover the following...
We will examine interfaces in action by writing code. We have the ElectricCar class that simulates an electric car.
Line 1: We use a file-scoped namespace.
Line 5: We define a property
CarOnwith a private setter to protect the state.Lines 7–18: We define the
StartTheCarmethod to enable the car if the key is valid.Lines 20–24: We define the
TurnTheCarOffmethod to update the car’s state to off and prints a notification message.Lines 26–36: We define the
Drivemethod to check the car’s state and allows driving only if the car is currently running.Lines 38–42: We define the
KeyValidprivate 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.
Line 3: We instantiate the
ElectricCar. ...