new keyword in 'hide' base class member

M

Man T

We can use the 'new' keyword to 'hide' a base class member.
But it seems the 'hide' is not a correct term, actually it is to 'show' the
base class member. Only 'override' keyword is to hide the base class member.
Any comment?
 
H

Hans Kesting

Man T used his keyboard to write :
We can use the 'new' keyword to 'hide' a base class member.
But it seems the 'hide' is not a correct term, actually it is to 'show' the
base class member. Only 'override' keyword is to hide the base class member.
Any comment?

Some example code to show the difference:

public class ClassA
{
public virtual void MethodNew()
{
Console.WriteLine("In MethodNew of ClassA");
}

public virtual void MethodOverride()
{
Console.WriteLine("In MethodOverride of ClassA");
}
}

public class ClassB: ClassA
{
public new void MethodNew()
{
Console.WriteLine("In MethodNew of ClassB");
}

public override void MethodOverride()
{
Console.WriteLine("In MethodOverride of ClassB");
}
}


When I then execute this:

ClassA ab = new ClassB();
ab.MethodNew();
ab.MethodOverride();

I get:

In MethodNew of ClassA
In MethodOverride of ClassB



Hans Kesting
 
B

Ben Voigt [C++ MVP]

Man T said:
We can use the 'new' keyword to 'hide' a base class member.
But it seems the 'hide' is not a correct term, actually it is to 'show'
the base class member. Only 'override' keyword is to hide the base class
member.
Any comment?

'override' doesn't hide the base member, it replaces it. So that existing
calls to the base member use the overriding version instead.

'new' hides the base member, so that it still exists and can be called by
functions that only know about the base class. But functions that know
about your derived class call the new version instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top