Key Concepts

Review core concepts you need to learn to master this subject

C# Interface

interface IAutomobile { string LicensePlate { get; } double Speed { get; } int Wheels { get; } } // The IAutomobile interface has three properties. Any class that implements this interface must have these three properties. public interface IAccount { void PayInFunds ( decimal amount ); bool WithdrawFunds ( decimal amount ); decimal GetBalance (); } // The IAccount interface has three methods to implement. public class CustomerAccount : IAccount { } // This CustomerAccount class is labeled with : IAccount, which means that it will implement that interface.

In C#, an interface contains definitions for a group of related functionalities that a class can implement.

Interfaces are useful because they guarantee how a class behaves. This, along with the fact that a class can implement multiple interfaces, helps organize and modularize components of software.

It is best practice to start the name of an interface with “I”.

Lesson 1 of 2
  1. 1
    Since programming is complex, it’s easy to make mistakes. For example, maybe we try to use an int like a string. This would cause a type error. C# has rules built-in that check for those mistakes b…
  2. 2
    For this lesson we will be designing a new set of transportation machines that satisfy the requirements of BOTH car designers and the highway patrol. First the highway patrol tells us: “Every autom…
  3. 3
    Our interface is complete! Pretty easy, right? As we design our automobile-like classes, we’ll need to implement this IAutomobile interface. In C#, we must first clearly announce that a class impl…
  4. 4
    The Sedan needs to satisfy more than the highway patrol’s rules (the IAutomobile interface). The car designers have asked that sedans are built and move in certain ways — it must have constru…
  5. 5
    We’ve completed a Sedan class that satisfies both car designers and highway patrol: it can be constructed and change speed, and it implements the IAutomobile interface. But sedans aren’t the only…
  6. 6
    The car designers have asked that trucks act a bit differently from sedans. Trucks need a new property called Weight. Whenever a truck is constructed, its number of wheels will depend on its weight…
  7. 7
    Now we have a Sedan class and Truck class that implement the IAutomobile interface. Though they have some different behaviors, they both have the properties and method defined in the interface: * d…
  8. 8
    Well done! In this lesson, you: * Learned that interfaces are useful to guarantee certain functionality across multiple classes * Built an interface using the interface keyword * Defined properties…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo