C# and Multiple Inheritance



Multiple Inheritance isn’t supported in C#. To implement multiple inheritances, use Interfaces.

Here is our interface PaintCost in class Shape −

public interface PaintCost {    int getCost(int area); }

The shape is our base class whereas Rectangle is the derived class −

class Rectangle : Shape, PaintCost {    public int getArea() {       return (width * height);    }    public int getCost(int area) {       return area * 80;    } }

Let us now see the complete code to implement Interfaces for multiple inheritances in C# −

Using System; namespace MyInheritance {    class Shape {       public void setWidth(int w) {          width = w;       }       public void setHeight(int h) {          height = h;       }       protected int width;       protected int height;    }    public interface PaintCost {       int getCost(int area);    }    class Rectangle : Shape, PaintCost {       public int getArea() {          return (width * height);       }       public int getCost(int area) {          return area * 80;       }    }    class RectangleDemo {       static void Main(string[] args) {          Rectangle Rect = new Rectangle();          int area;          Rect.setWidth(8);          Rect.setHeight(10);          area = Rect.getArea();          // Print the area of the object.          Console.WriteLine("Total area: {0}", Rect.getArea());          Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));          Console.ReadKey();       }    } }
Updated on: 2020-06-19T08:35:22+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements