0

new and** virtual** Keyword are the same as i feel,since new Keyword in the method hides the same base class methods whereas virtual keyword override the base class,So what is difference between new and virtual ,and how to determine when to use anyone of it?

[CODE]
        public class Base123
    {
        public void add()
        {
            Console.WriteLine ("Hi tis is A");
        }
                public virtual void a()
        {
            Console.WriteLine ("Hi its Base");
        }
    }
        class Derived123:Base123
    {
        public new void add()
        {
            Console.WriteLine ("Hi this B");
        }
                public override void a()
        {
            Console.WriteLine ("Hi its derived");
        }
        public static void Main (string[] args)
        {
            Derived123 d=new Derived123(5);
            d.add ();
                        d.a();
        }
    }
[/CODE]   
2
Contributors
1
Reply
23
Views
4 Years
Discussion Span
Last Post by Ketsuekiame
0

It's probably easier to explain with an example;

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

public class NewDerived : BaseClass
{
    public new void PrintName()
    {
        Console.WriteLine("New");
    }
}

public class OverrideDerived : BaseClass
{
    public override void PrintName()
    {
        Console.WriteLine("Derived");
    }
}

...
BaseClass baseOne = new NewDerived();
BaseClass baseTwo = new OverrideDerived();

baseOne.PrintName(); // Output: Base
baseTwo.PrintName(); // Output: Derived

((NewDerived)baseOne).PrintName(); // Output: New
((OverrideDerived)baseTwo).PrintName(); // Output: Derived

So new, replaces the old method, but doesn't actually override it (hence why it says you're hiding the method). So you can call the original base method from the base class, if you wanted. Whereas when you use override, the class will look up the overridden method and use that one instead.

There are very few reasons you'd want to use new instead of override, so make sure that the design is correct first! :)

Forgot to mention, you can use the new keyword without the base method being marked virtual. But then you wouldn't be able to use override.

Edited by Ketsuekiame

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.