Interface in C#: Part 1

In this article we will look at the common things that need to be done to declare and implement an interface.

An interface looks like a class that can have a set of properties, methods, events and indexers, but has no implementation. The interface does not have an implementation of properties, methods, events and indexers because they are inherited by classes and structs, which must provide an implementation for each interface member.

An interface can be used to hide implementation details of classes from each other and it allows various objects to interact easily. It provides a separation between interface and implementation.

An interface is not only a contractual obligation to implement certain methods, properties, events and indexes but also provides a very low coupling between two classes. Interfaces in C# are provided as a replacement of multiple inheritances of classes because C# does not support multiple inheritances of classes.

Interfaces and abstract classes have similar purposes. Generally, an interface should be used when the implementation of the members it defines is not fixed, or when it is known that a single class requires the contents of several interfaces. Where the functionality of some members is fixed and the limited multiple inheritance facility is not required, abstract classes may be more appropriate.

How to create an Interface

Syntax

Interface interface_name
{
}
 

1. An interface defines a signature of methods, events and indexes but not an implementation.

Example:  An interface IVehicle that has a method "Speed()"  with its definition/implementation.

interface IVehicle
{
     double Speed(int distance, int hours)
     {
         double speed = 0.0d;
         speed = distance / hours;
         return speed;
     }
 } 

We execute the above code and get an error such as:

Error : 'IVehicle.Speed(int, int)': interface members cannot have a definition

So the interface has only signature of methods, no implementation.

2. Interface members are public by default; there is no need to use an access specifier.

Example

An interface IVehicle that has a method "Speed()" signature and has a public access specifier.

interface IVehicle
{
     public double Speed(int distance, int hours);       
 } 

We execute the above code and get an error such as:

Error:  The modifier 'public' is not valid for this item          

So the interface members don't have any access specifier, by default they are public.

3. By default an interface is internal and we can't declare it private, protected or protected internal because it is always inherited by classes or structs.

Example: An interface IVehicle that has a private access specifier:

private interface IVehicle
{

    double Speed(int distance, int hours);

We execute the above code and get an error such as:

Error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

So by default the interface itself is internal and we can also use a public access specifier but can't use private, protected and protected internal. One more thing is that class and struct also are by default internal as well as interfaces.  

4. An interface does not have fields; in other words we can't declare variables in an interface.

Example: An interface IVehicle that has two fields, one speed (not initialized) and another hours (initialized).

interface IVehicle
{
    double speed;
    decimal hours = 0.0m;

We execute the above code and get two errors, the same error for each field; see:

Error  : Interfaces cannot contain fields           

So we can't declare a field in the interface.

5. When an interface is inherited by a class or a struct then need to implement all members of the interface in that class. An interface is inherited by a colon (:) sign on the class or struct.

Example

An interface "IVehicle" that has methods "Speed()" and "IVehicle" inherited by the Vehicle class.

interface IVehicle
{
   
double Speed(int distance, int hours);       
}
class Vehicle:IVehicle
{       
}

We execute the above code and get an error such as:

Error :  'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)'

So we should implement all members (method, properties etc) of the interface in classes that inherit an interface. 

6. Should use a public access specifier for inherited members from an interface to a class. By default all members are public in interfaces but when we implement a method in a class we need to define it as public.

Example

An interface "IVehicle" that has a method "Speed()" signature and a class "Vehicle" that inherits the "IVehicle" interface.

interface IVehicle
{
   
double Speed(int distance, int hours);       
}
 

class Vehicle:IVehicle
{
   
double Speed(int distance, int hours)
    {
       
double speed = 0.0d;
        speed = distance / hours;
       
return speed;
     }
}

We execute the above code and get an error such as:

Error : 'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)'. 'Vehicle.Speed(int, int)' cannot implement an interface member because it is not public.         

So we need to use a public access specifier when we implement an inherited interface member in a class because all members are public in an interface. 

7. We can't create an instance of an interface but we can declare a variable of a particular type interface.

Example: An interface "IVehicle"  and a class "Vehicle" that inherits the "IVehicle" interface. See:

interface IVehicle
{       
} 

class Vehicle:IVehicle
{   
    
IVehicle veh = new IVehicle();          
}

We execute the above code and get an error such as:

Error: Cannot create an instance of the abstract class or interface 'IVehicle'   

So we can't create an instance of the interface as well as abstract class because an interface is always inherited but can create a variable of an interface type.

How can implement an Interface on a class

In the following code the "IVehicle" interface has a "Speed()" method signature and its inherited by the "Vehicle" class so the speed() method implementation is in the derived class. After that in the "Program" class a "Vehicle" instance calls the "Speed()" method:

using System;

namespace InterfaceExamples
 {
     interface IVehicle
    {
        
double Speed(int distance, int hours);
    }
     class Vehicle : IVehicle
    {
        
public double Speed(int distance, int hours)
        {
            
double speed = 0.0d;
            speed = distance / hours;
            
return speed;
        }
    }

    class Program
    {
        
static void Main(string[] args)
        {
            
int distance =500,hours=2;
            
double speed = 0.0;
            
Vehicle objVehicle = new Vehicle();
            speed = objVehicle.Speed(distance, hours);
            
Console.WriteLine("speed is {0}", speed);
            
Console.Read();
        }       
    }

Interface-in-Csharp.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all