C Sharp Interface

C# Interface

In C#, an interface can be understood as a blueprint of a class. All the methods declared inside the interface are abstract methods, and thus it is similar to an abstract class. The method body is not present in a C# interface. Also, a C# interface cannot be instantiated. A class can’t achieve multiple inheritances, but an interface can. Without any method body, it is best suitable for achieving fully abstraction. Class or struct is used to provide its implementation. Again, the implementation of all the methods declared inside the interface is provided by the class or struct which implements the interface.

Example:

using System;  
public interface Flower  
{  
    void color();  
}  
public class Rose : Flower  
{  
    public void color()  
    {  
        Console.WriteLine("Red Rose!!");  
    }  
}  
public class Lily : Flower  
{  
    public void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
}  
public class TestInterface  
{  
    public static void Main()  
    {  
        Flower f;  
        f = new Rose();  
        f.color();  
        f = new Lily();  
        f.color();  
    }  
}

Output:

Explanation:

In the above example, the interface has the color() method. The Rose and Lily classes provide its implementation. The output of both the classes will be displayed on the console screen.

Explicit use of the public and abstract keywords for an interface method:

Example:

using System;  
public interface Flower  
{  
    public abstract void color();  
}  
public class Rose : Flower  
{  
    public void color()  
    {  
        Console.WriteLine("Red Rose!!");  
    }  
}  
public class Lily : Flower  
{  
    public void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
}  
public class TestInterface  
{  
    public static void Main()  
    {  
        Flower f;  
        f = new Rose();  
        f.color();  
        f = new Lily();  
        f.color();  
    }  
}

Output:

Explanation:

In the above example, a compile time error will be displayed. The public and abstract keywords cannot be explicitly used for an interface method because the interface methods are by default public and abstract. Here, both the modifiers, ‘public’ and ‘abstract’ are considered invalid for the interface method ‘color’.