एक वर्ग बनाते समय, पूरी तरह से नए डेटा सदस्यों और सदस्य कार्यों को लिखने के बजाय, प्रोग्रामर यह निर्दिष्ट कर सकता है कि नए वर्ग को मौजूदा वर्ग के सदस्यों का उत्तराधिकारी होना चाहिए। इस मौजूदा वर्ग को आधार वर्ग कहा जाता है, और नए वर्ग को व्युत्पन्न वर्ग कहा जाता है।
एक वर्ग को एक से अधिक वर्ग या इंटरफ़ेस से प्राप्त किया जा सकता है, जिसका अर्थ है कि यह कई आधार वर्गों या इंटरफेस से डेटा और कार्यों को इनहेरिट कर सकता है।
C# में बेस क्लास का सिंटैक्स निम्नलिखित है -
<access-specifier> class <base_class> { ... } class <derived_class> : <base_class> { ... }
आइए एक उदाहरण देखें -
उदाहरण
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } }