Basics of Inheritance and using Virtual Methods and Overriding

Virtual methods are use so that we can use them in different class again with the same method names. Inheritance helps us define classes and use the base and existing classes which are defined and inherit their methods and members.

Program.CS
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace CustomerOrders  
  7. {  
  8.    class Program  
  9.    {  
  10.       static void Main(string[] args)  
  11.       {  
  12.          var ph = new Phones();  
  13.          ph.itemid = 102;  
  14.          ph.itemname = "Samsung s3";  
  15.          ph.purchase();  
  16.          Tablets tb = new Tablets();  
  17.          tb.tabname = "IPAD";  
  18.          tb.tabmodel = "Apple Gen 1";  
  19.          tb.purchase();  
  20.          Console.ReadKey();  
  21.       }  
  22.    }  
  23. }  
Items.CS
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace CustomerOrders  
  7. {  
  8.    class Items  
  9.    {  
  10.       public int itemid { getset; }  
  11.       public string itemname { getset; }  
  12.       public virtual void purchase()  
  13.       {  
  14.          Console.WriteLine("Purchasing item : {0}", itemname);  
  15.       }  
  16.    }  
  17.    class Phones : Items  
  18.    {  
  19.       public int IMEI { getset; }  
  20.    }  
  21.    class Tablets : Items  
  22.    {  
  23.       public String tabmodel { getset; }  
  24.       public string tabname { getset; }  
  25.       public override void purchase()  
  26.       {  
  27.          Console.WriteLine("Tablet name for offer is :{0} and model is :{1}", tabname,tabmodel);  
  28.       }  
  29.    }  
  30.    class Ipods : Items  
  31.    {  
  32.       public int ipodgeneration { getset; }  
  33.    }  
  34.    class Iphone:Phones  
  35.    {  
  36.       public string phoneversion { getset; }  
  37.    }  
  38. }