Monday, June 27, 2011

What is the difference between hiding and overriding for casting related matters?

When you use virtual+new, the method definition of base class is hided by the definition provided in child class (called method hiding) . In this case, method of the class, whose object is created, will be called.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  //Will give output Base
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public new void foo()
        {
            Console.WriteLine("Child");
        }
    }


In second case, where you want to use virtual+override, Thats method overriding. In this case child class function will be called when you create object using casting.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  // output will be "Child"
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public override void foo()
        {
            Console.WriteLine("Child");
        }
    }


You can also combine both method overriding and hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }

No comments:

Post a Comment