June 20, 2011

code example for Upcasting/Downcasting in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{


    public  class EMP
    {
        int ID;
        String  NAME;


        public EMP()
        {


        }
       public EMP(int id,String name)
        {
            this.ID =id;
            this.NAME = name;


        }
        public  int GetID
        {
            get{


                return this.ID;
            }


            set{


                this.ID=value ;
            }
        }


        public string  GetName
        {
            get
            {


                return this.NAME ;
            }
            set
            {


                this.NAME = value;
            }
        }


       
    }


    public class SalesEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public SalesEmp()
        {


        }
        public SalesEmp(int DepId,String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }
      
        public int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }








    class Program
    {
        static void Main(string[] args)
        {
            EMP e = new EMP();
            SalesEmp se = new SalesEmp(1, "SALE");


            e = se;//upcasting




            if (se is EMP)
            {
                se.GetName = "ABC";
                se.GetID = 123;


            }


            SalesEmp s1 = (SalesEmp)e;//downcasting
           
            Console.WriteLine(s1.GetID);
            Console.WriteLine(s1.GetName);
            Console.WriteLine(s1.GetDepID);
            Console.WriteLine(s1.GetDepName);
        }
    }
}


below is the o/p


No comments:

Post a Comment