We generally apply the concept of inheritance to implement a IS-A relationship. For example to implement a relationship that says an Apple is a Fruit or Earth is a cosmic object. We use inheritance very carefully so that it does not lead to long complex/un-maintainable object hierarchies, but to implement very specific object hierarchies with least coupling as possible. Below is simple to show how we implement Inheritance in C# -
Parent Class - VisibleObject
using System; namespace Inheritance { public class VisibleObject { public string Visibility { get; set; } public void Copy() { Console.WriteLine("The Object was Copied"); } public void Move() { Console.WriteLine("The object was moved"); } } }
Child Class - Verbiage
Note how we use the ':' operator to inherit parent class
using System; namespace Inheritance { public class Verbiage : VisibleObject { public float FontSize { get; set; } public string Font { get; set; } public string Text { get; set; } public void AddHtml(Verbiage verbiage) { string html = "<html><body><div style=\"visibility: " + verbiage.Visibility + "\"><font type=\"" + verbiage.Font + "\" size=\"" + verbiage.FontSize + "\">" + verbiage.Text + "</font></div></body></html>"; Console.WriteLine("Added HTML! {0}", html); } } }
Usage -
Note how the parent property and methods are accessed via the child object
namespace Inheritance { class Program { static void Main(string[] args) { var verbiage = new Verbiage(); //sets parent property verbiage.Visibility = "hidden"; verbiage.Font = "Arial"; verbiage.FontSize = 12; verbiage.Text = "Best Website on the internet!"; verbiage.AddHtml(verbiage); //calls parent methods verbiage.Copy(); verbiage.Move(); } } }