overriding and new on derived methods

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello all,

I've just used the new keyword on an inherited method as the derived on is a
public int. What's the difference between the 2?

Thanks,

Jon
 
Jon,

What are the 2?

The *new* keyword suppresses the worning that the compiler issues when you
hide a base class method. Using this keyword you tell the compiler that you
know what you are doing.

Consider the following snippet:

class Foo
{
public void Fun()
{
}
}

class Bar: Foo
{
public void Fun()
{
}
}

The moethod Fun is not decalred as a *virtual* method. It means that you are
hiding the base implementation. See the following code for example

Bar b = new Bar();
Foo f = b;

b.Foo() --> Calls Bar.Fun
f.Foo() --> calls Foo.Fun

Because this is error prone code the compilier warns you for the pitfall. If
this is exactly what you want and you are aware of the problems that it
might cause, just use the *new* keyword in the Bar's method declaration and
the compiler will suppress the warning.

HTH
Stoitcho Goutsev (100) [C# MVP]
 
Back
Top