new and Virtual.. differences...?

  • Thread starter Thread starter superfrog
  • Start date Start date
S

superfrog

Hi there,

while trying to learn polymorphism, i am confused between
the 2.

=======================================================

class Person
{
...
public void someMethod()
{
//do something
}
}
class Guy :Person
{
public new void someMethod()
{
// do something
}
}

===============================================


what is the difference between using the "New" keyword
(int the above code) and using a "Virtual" in the base
class and the "override" in the derive class?

thank you very much.
 
superfrog

Consider this example below. WHen you look at the output you should get

A-X
A-Y
A-X
B-Y

What this shows is that when the base class runs PrintIt and calls this.X or this.Y it runs the
inherited class's implementation on the virtual Y method but doesn't see the new implemnetation
of X so it runs its own version of it.


using System;
namespace TestNewAndVirtual
{
public class A
{
public string X
{
get { return "A-X"; }
}
public virtual string Y
{
get { return "A-Y"; }
}
public virtual void PrintIt()
{
Console.WriteLine ( this.X );
Console.WriteLine ( this.Y );
}
}
public class B : A
{
new public string X
{
get { return "B-X"; }
}
public override string Y
{
get { return "B-Y"; }
}
public static void Main()
{
A a = new A();
B b = new B();
a.PrintIt();
b.PrintIt();
Console.ReadLine();
}
}
}
 
Back
Top