Interfaces in C# Explained

By | August 28, 2014

 

Interface in C# contains definitions for a group of related features that a struct or a class can decide to implement.

By implementing an interface, you are able to incorporate behaviours from different sources into your class. This feature is very useful particularly considering that C# does not support Inheritance from multiple classes. Also as structs do not support inheritance, you can use interface to simulate inheritance from structs.

An interface has the following properties:

• An interface is like an abstract base class. Any class or struct that implements the interface must implement all its members.
• An interface can’t be instantiated directly. Its members are implemented by any class or struct that implements the interface.
• Interfaces can contain events, indexers, methods, and properties.
• Interfaces contain no implementation of methods.
• A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

You can define an Interface in C# using the interface keyword as shown below:

interface IEquatable<T>
{
    bool Equals(T obj);
}

 

Interfaces can contain the following:

• methods
• properties
• events
• indexers
• any combination of the above four member types.

An interface can’t contain the following:

• constants
• fields
• operators
• instance constructors
• destructors
• types

Interface members are automatically public, and they can’t include any access modifiers. Members also can’t be static

To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
When a class or struct decides to implement an interface, it must provide an implementation for all of the members that the interface defines.
The interface itself does not provide any implementation that a class or struct can inherit. However, if a base class implements an interface, any class that’s derived from the base class inherits that implementation.

The following example shows an implementation of the IEquatable interface. The implementing class, Car, must provide an implementation of the Equals method.

interface IEquatable<T>
{
    bool Equals(T obj);
}

public class Car : IEquatable<Car>
{
    public string Make {get; set;}
    public string Model { get; set; }
    public string Year { get; set; }

    // Implementation of IEquatable<T> interface
    public bool Equals(Car car)
    {
        if (this.Make == car.Make &&
            this.Model == car.Model &&
            this.Year == car.Year)
        {
            return true;
        }
        else
            return false;
    }
}

References:
Interfaces (C# Programming Guide)

Leave a Reply