- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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(); } } }
Advertisements