overriding non virtual methods, why bother with override at all then

N

news.microsoft.com

Hi,

It is possible to override a non virtual method with the "new" keyword

So how is this different from specifying a method as virtual then
providing the override keyword?

Is there any differences between these two methods of overriding?

Thanks.
 
N

Nicole Calinoiu

There is a difference, and it lies in the behaviour of objects cast down to
their base classes. For example, let's say you have a class A which has a
virtual method. Class B inherits from A and overrides the virtual method.
If you cast down an object of type B to type A and execute the overridden
method, you will be executing the implementation of the method defined by
class B. However, if the method is not virtual, and it is hidden by a new
method in class B, execution of the method against an object of type B cast
down to type A will result in execution of the class A implementation of the
method. Run the following console application to verify this for yourself:

class ConsoleDemo
{
static void Main()
{
Console.WriteLine("Working with a B object:");
B b = new B();
b.ShowOverride();
b.ShowNew();

Console.WriteLine();
Console.WriteLine("Working with a B object cast down to an A
object:");
A a = (A)b;
a.ShowOverride();
a.ShowNew();

Console.ReadLine();
}
}

class A
{
public virtual void ShowOverride()
{
Console.WriteLine("A.ShowOverride()");
}

public void ShowNew()
{
Console.WriteLine("A.ShowNew()");
}
}

class B : A
{
public override void ShowOverride()
{
Console.WriteLine("B.ShowOverride()");
}

public new void ShowNew()
{
Console.WriteLine("B.ShowNew()");
}
}
 
R

Ray Hsieh (Djajadinata)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

The difference is that when you make a method virtual, it's virtual all
the way up. When you *new* a non-virtual method, however, the base
class's version of the method is *hidden*, so up the inheritance
hierarchy, that method is still non-virtual. It is only virtual from the
class where you specify new virtual, down the inheritance chain.

news.microsoft.com wrote:

| Hi,
|
| It is possible to override a non virtual method with the "new" keyword
|
| So how is this different from specifying a method as virtual then
| providing the override keyword?
|
| Is there any differences between these two methods of overriding?
|
| Thanks.
|
|


- --
Ray Hsieh (Djajadinata)
ray underscore usenet at yahoo dot com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQE/m/slwEwccQ4rWPgRAsLyAJ9WdUuOU0vOPq5eLc03piMrxVTPygCeOou4
fAIjR2+mPM5rUBd+fqyYJnk=
=fN0g
-----END PGP SIGNATURE-----
 

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