0

I have read many of the stack-overflow questions and answers about "Method hiding,new keyword,overriding,and their differences but still i am confused why NEW keyword is using ? here is my doubt,
(1.)

class Base
{
    // base property
    public virtual string Name
    {
        get { return "Base"; }
    }
}
class New : Base
{
    // new property, hides the base property
    public new string Name
    {
        get { return "New"; }
    }
}
 New n = new New();
// type of `n` variable is `New`, and `New.Name` is not virtual,
// so compiler sees `n.Name` as a completely different property
Console.WriteLine(n.Name); // prints "New"

But my question is if we use New n = new New(); with out new keyword also, it will print the same result "New " .Then what is the necessity of new keyword ? WHY and WHEN we use New keyword ? Can any one tell me exactly where it is useful ? With some examples ?


(2.)

 class Program
{
    public class A
    {
        public virtual string GetName()
        {
            return "A";
        }
    }

    public class B : A
    {
        public override string GetName()
        {
            return "B";
        }
    }

    public class C : B
    {
        new public string GetName()
        {
            return "C";
        }
    }

    static void Main(string[] args)
    {
        A instance = new C();
        Console.WriteLine(instance.GetName());
        Console.ReadLine();
    }

}

In the above example its printing B Why not C ? , My question is if new keyword will hide the base class member then why here B is not hiding ?I read many stack overfolw answers but still i am confused with new keyword some one please clear my doubt

Arun CM
  • 3,345
  • 2
  • 29
  • 35
  • You basically remove the warning. See the duplicate for an explanation of why the warning is shown. – Sam Leach Feb 10 '14 at 12:56
  • 1) You are hiding *base and allowed to be overridden implementation*, see [this](http://stackoverflow.com/questions/1334254/how-can-i-call-the-base-implementation-of-an-overridden-virtual-method), when hiding, however, you can easily get base, by casting. 2) This is intended, [here](http://dotnetfiddle.net/3P4VXZ) is how you use it. – Sinatr Feb 10 '14 at 13:30

0 Answers0