Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using "new" when hiding methods?

Tags:

c#

.net

Why is it necessary to use the new keyword when a method shall be hidden?

I have two classes:

public class Parent
{
    public void Print()
    {
        Console.WriteLine("Parent");
    }
}

public class Child : Parent
{
    public void Print()
    {
        Console.WriteLine("Child");
    }
}

Following code produces the given output:

Parent sut = new Child();
sut.Print();

Output: Parent

Child sut = new Child();
sut.Print();

Output: Child

I understand that this might be a problem if it the hiding was not intended but is there any other reason to use "new" (excepted avoding of warnings)?

Edit:

May be I was not clear. It is the same situation like:

public void foo(Parent p)
{
 p.Print();
}

which is called:

Child c = new Child;
foo (c);c
like image 531
HerrLoesch Avatar asked Aug 11 '10 13:08

HerrLoesch


1 Answers

No, but avoiding the warnings is incredibly important. The bugs caused by hiding can be insiduous, and after C++ (which just let you do it) both Java and C# chose two different ways to prevent them.

In Java, it is not possible to hide a base classes methods. The compiler will scream bloody murder if you try to do it.

In C#, there is the "new" keyword. It allows you to be explicit that you want to hide a method, and the compiler will warn you if you are not using it. Many developers make it a rule to have code compiler with no warnings because warnings can be a sign of bad code.

After all that, I have never had to use hiding. I would carefully consider why I was even considering using it, since its behavior is strange and almost never what I want.

like image 200
Chris Pitman Avatar answered Oct 27 '22 15:10

Chris Pitman