#455 – Define an Interface Based on Existing Members of a Class

You can use Visual Studio to define a new interface, based on existing members of a class.  This is also known as extracting an interface.

For example, suppose we have an existing Cow class that doesn’t currently implement any interfaces.  A Cow has properties like Name, MooLog and Motto, and methods like Moo, Dance and Burp.

We can create a new IMoo interface that consists of a Moo method and a MooLog property.  Since Cow already implements both of these members, we can extract the interface from the class.

Right-click on the Cow class name and select Refactor and then Extract Interface.

We then give the new interface a name (e.g. IMoo) and select the members of the existing class that should be part of the interface.

After clicking OK, Visual Studio generates the new interface.

Cow now inherits from IMoo.