C# Method Hiding or Method Shadowing

Program : Accessing derived class objects by Base class Ref.Variable

using System;

namespace Polymorphism
{
    class MethodHidingOrShadowing
    {
        public class Person
        {
            public void Print()
            {
                Console.WriteLine("I am Person Method");
            }
        }

        class Employee: Person
        {
            public new void Print() //Add new keyword to skip the warning
            {
                Console.WriteLine("I am Employee method");
            }
        }

        class Manager: Employee
        {
            public new void Print() //Add new keyword to skip the warning
            {
                Console.WriteLine("I am Manager method");
            }
        }

        static void Main(string[] args)
        {
            Person p;

            p = new Person();
            p.Print();  //I am base

            p = new Employee();
            p.Print();  //I am base

            p = new Manager();
            p.Print(); //I am base

            Console.ReadKey();
        }
    }
}


Output

I am Person Method
I am Person Method
I am Person Method

Changes: Casting derived class objects to refer to parent objects

using System;

namespace Polymorphism
{
    class MethodHidingOrShadowing
    {
        public class Person
        {
            public void Print()
            {
                Console.WriteLine("I am Person Method");
            }
        }

        class Employee: Person
        {
            public new void Print() //Add new keyword to skip the warning
            {
                Console.WriteLine("I am Employee method");
            }
        }

        class Manager: Employee
        {
            public new void Print() //Add new keyword to skip the warning
            {
                Console.WriteLine("I am Manager method");
            }
        }

        static void Main(string[] args)
        {
            Person p = new Person();
            p.Print();              //I am base

            Employee e = new Employee();
            e.Print();              //I am employee
            ((Person)e).Print();    //I am Person

            Manager m = new Manager();
            m.Print();              //I am manager
            ((Employee)m).Print();  //I am Employee
            ((Person)m).Print();    //I am person

            Console.ReadKey();

            Console.ReadKey();
        }
    }
}

Note: 

1. Inward casting is possible in C#.  (moving from outer scope to inner scope)

2. Outward casting is not possible.  (moving from inner scope to outer scope)

    That is, we can cast manager type as employee type and employee type as person type. But casting person type as employee type and casting employee type as manager type is not possible.

No comments:

Post a Comment