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]   

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.