new keyword in 'hide' base class member

  • Thread starter Thread starter Man T
  • Start date Start date
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?
 
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
 
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.
 
Back
Top