Learn C#: Interfaces and Inheritance
Organize, secure, and simplify your code with interfaces and inheritance.
StartKey Concepts
Review core concepts you need to learn to master this subject
C# Interface
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”.
Interfaces
Lesson 1 of 2
- 1Since 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…
- 2For 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…
- 3Our 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…
- 4The 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…
- 5We’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…
- 6The 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…
- 7Now 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…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory