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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CustomerOrders
- {
- class Program
- {
- static void Main(string[] args)
- {
- var ph = new Phones();
- ph.itemid = 102;
- ph.itemname = "Samsung s3";
- ph.purchase();
- Tablets tb = new Tablets();
- tb.tabname = "IPAD";
- tb.tabmodel = "Apple Gen 1";
- tb.purchase();
- Console.ReadKey();
- }
- }
- }
Items.CS
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CustomerOrders
- {
- class Items
- {
- public int itemid { get; set; }
- public string itemname { get; set; }
- public virtual void purchase()
- {
- Console.WriteLine("Purchasing item : {0}", itemname);
- }
- }
- class Phones : Items
- {
- public int IMEI { get; set; }
- }
- class Tablets : Items
- {
- public String tabmodel { get; set; }
- public string tabname { get; set; }
- public override void purchase()
- {
- Console.WriteLine("Tablet name for offer is :{0} and model is :{1}", tabname,tabmodel);
- }
- }
- class Ipods : Items
- {
- public int ipodgeneration { get; set; }
- }
- class Iphone:Phones
- {
- public string phoneversion { get; set; }
- }
- }