Interface
Interface is exactly same as that of Abstract class with some differences. Another way to achieve abstraction in C#, is using interfaces. Interface can only have abstract methods (methods without body) inside it and it cannot be instantiated.
Abstract class | Interface |
---|---|
It can have fields | It cannot have fields |
It can have normal methods(Methods with body) | It cannot have normal methods(Methods with body) |
Its members can have access modifiers | Its members cannot have access modifiers |
It can inherit from another abstract class or another interface | It can inherit from another interface only and cannot inherit from an abstract class |
While overriding abstract methods, Override keyword is mandatory | While overriding abstract methods, Override keyword is not mandatory |
Multiple inheritance is not possible | Multiple inheritance is possible |
CODE
EG 1 . Creating 2 Interfaces called IShape and IObject and Inheriting to Class Circle.
interface IShape {
    //In interface no need to use Abstract keyword before abstract methods.
    double Area();
    double Volume();
    double Perimeter();
}
interface IObject {
    string message();
}
//Multiple Inheritance is possible when it comes to interface
class circle : IShape,IObject {
    public double radius, height;
    public double Area() {
        return Math.PI * radius * radius;
    }
    public double Volume() {
        return Area() * height;
    }
    public double Perimeter() {
        return 2 * Math.PI * radius;
    }
    public string message() {
        return "Welcome";
    }
}
class Program {
    static void Main(string[] args) {
        //Upcasting
        IShape i1 = new circle();
    }
}
(Click Here, For more exercises)