This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Interfaces

The twenty-first part of the C# Object-Oriented Programming tutorial completes the investigation of polymorphism in the C# programming language. This instalment describes the use of interfaces to determine required members in classes that implement them.

Interface Inheritance

The last topic of discussion for interfaces is the concept of inheritance. As classes can inherit functionality from a base class, so interfaces can inherit from other interfaces. When one interface inherits from another, the members of the parent interface do not need to be repeated in the child's code. However, all of the members from both interfaces must be included in a class that implements the child interface. These can be implemented either implicitly or explicitly.

Interface inheritance uses the concept of name hiding. As with classes, if a member is created in a parent interface and duplicated in a child interface the child's version must use the "new" keyword to hide the parent interface's version.

To demonstrate interface inheritance we will create a new interface for all animals. IPrey and IPredator will be adjusted so that they inherit from this new, "IAnimal" interface. To begin, add a new interface file named "IAnimal". Add a single property to the interface to hold the animal's name.

interface IAnimal
    string Name { get; set; }

To indicate that the IPrey and IPredator interfaces are children of IAnimal, adjust the declarations for the two interfaces as follows:

// IPrey.cs

interface IPrey : IAnimal

// IPredator.cs

interface IPredator : IAnimal

Now that the interfaces inherit from IAnimal, the Cat and Fish classes must also implement IAnimal's members before the program can be compiled. To declare the property implicitly, add the following code to both classes:

private string _name;

public string Name
    get { return _name; }
    set { _name = value; }

The choice of data type for animal variables is now interesting. Both the Cat and Fish classes can be instantiated and assigned to IAnimal or IPredator variables. If used as an IAnimal object, only the Name property will be present. If used as an IPredator object, the members from the IAnimal and IPredator interfaces are available but other members of the class are invisible.

The following code shows the full extent of the polymorphism provided by a Fish object. Note that the object can be assigned to variables of any of the interface types that Fish implements:

Fish bubbles = new Fish();
IAnimal animal = bubbles;
IPredator predator = bubbles;
IPrey prey = bubbles;
15 April 2008