Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

upcasting and downcasting in c#

/*
Upcasting: conversion from a derived class to a base class
Downcasting: conversion from a base class to a derived class
All objects can be implicitly converted to a base class reference

Upcasting is used when we need to develop a code that deals with only the parent class. 
Downcasting is used when we need to develop a code that accesses behaviors of the child class
*/
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Manager : Employee
    {
        public int ManagerID { get; set; }
        public string Posting { get; set; }
    }


    public class Program
    {
        static void Main(string[] args)
        {
            // upcasting
            Manager manager = new Manager();
            Employee employee = manager; // upcasting 
            /*
            both manager and employee object actullay pointng the same object in memory. 
            Just have diffrenct view. 
            employee does not have access to ManagerID,Posting
            manager have access all; 
			*/
            manager.FirstName = "John";
            employee.FirstName = "Sr. John";

            Console.WriteLine(manager.FirstName); // Sr. John
            Console.WriteLine(employee.FirstName); // Sr. John

            Manager manager2 = (Manager)employee; // downcast

            /*
             Casting can throw an exception if the conversion is not successful.We can use the as
             keyword to prevent this.If conversion is not successful, null is returned.
            */

            Manager manager3 = employee as Manager;
            if (manager3 != null)
            {
              // do something
            }
          
            // or
            if (employee is Manager)
            {
                var manager4 = (Manager)employee;
              // do something
            }
        }
    }
 
PREVIOUS NEXT
Tagged: #upcasting #downcasting
ADD COMMENT
Topic
Name
6+9 =