Translate

Friday, July 19, 2013

Difference between override and new C#

The difference between override and new occurs when you cast a Child class into the Parent class.

When a child is cast into a parent and then you call a method on that instance, the child class method will be called only if it is an override.

using System;
 
namespace ConsoleApplication
{
 
    public class Test
    {
        public static void Main()
        {
            var chldA=new ChildA();
            var chldB = new ChildB();
 
            /*This is simple and straight forward*/
            Console.WriteLine(chldA.CallMe());// prints ChildA
            Console.WriteLine(chldB.CallMe());// prints ChildB
 
 
            /*Cast child into the parent*/
            var p1 = (Parent)chldA;
            var p2 = (Parent)chldB;
 
           
            /*This is where the subtle difference is*/
            Console.WriteLine(p1.CallMe());// prints Parent
            Console.WriteLine(p2.CallMe());// prints ChildB
        }
    }
 
    public class Parent
    {
        public virtual string CallMe()
        {
            return "Parent";
        }
    }
 
    public class ChildA : Parent
    {
        public new string CallMe()//new
        {
            return "ChildA";
        }
    }
 
    public class ChildB : Parent
    {
        public override string CallMe()//override
        {
            return "ChildB";
        }
    }
 
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator