3.4.5 How to Implement an Interface

Once we have added and defined an interface we need classes to implement that interface. Let's revisit the ICleanable interface we defined in a previous article.

We want classes that are "cleanable" to have these two members in them. So let's go to the Restroom class and implement the interface by adding after the class header.

As soon as we do this, Visual Studio will check to make sure that the class has those members implemented somewhere. Since we don't in this class, we will get errors.

Let's implement OrganizeSupplies first. It is important to note that it doesn't matter how the class implements the method only that it does.

Now let's try to give the OrganizeSupplies a parameter. Note that we get an error saying it doesn't implement OrganizeSupplies correctly. Visual Studio is very picky about following the interface very closely.

Now let's implement the property. I have added a backing field for isCleaned and assigned it a value in the OrganizeSupplies method. Once the property is added the class implements the ICleanable interface fully and the errors go away.

Many classes can implement the same interface. Booth is also something that can be cleaned to we can implement the interface on that class as well.

And when we implement the method the method body will determine how the method functions.