Polymorphism in C# or is it .NET?

  • Thread starter Thread starter Alex
  • Start date Start date
A

Alex

I have a Base class with virtual member, I have 4 levels of derived classes,
but only the first 2 levels override the virtual member, the last 2 don't.
When I create a base type reference to most derived type, then invoke
virtual member, base type member is invoked. I expected most derived
implementation of virtual member to be invoked.

So is the rule:

When object that object reference points to does not have virtual member
implmented, invoke object reference type's virtual member?
 
Hi Alex

A little code would help.

You should have something like:

class A
{
public virtual string a() { return "A";}
}

class B:A
{
public override string a() { return "B";}
}

class C:B
{
public override string a() { return "C";}
}

class D:C
{
}



Now if you do:

A a = new D();

string g = a.a();

then g is going to return "C" , is this your question?

Hope this help,
 
Hi Alex

A little code would help.

You should have something like:

class A
{
public virtual string a() { return "A";}
}

class B:A
{
public override string a() { return "B";}
}

class C:B
{
public override string a() { return "C";}
}

class D:C
{
}



Now if you do:

A a = new D();

string g = a.a();

then g is going to return "C" , is this your question?

Hope this help,

Not true, I tried this and g returns "A".
 
I have a Base class with virtual member, I have 4 levels of derived
classes, but only the first 2 levels override the virtual member, the
last 2 don't. When I create a base type reference to most derived
type, then invoke virtual member, base type member is invoked. I
expected most derived implementation of virtual member to be invoked.

So is the rule:

When object that object reference points to does not have virtual
member implmented, invoke object reference type's virtual member?

Sorry, my code had all the derived classes dervining from the base class
instead of forming an inheritance chain, so it is true that the most derived
class' virtual method will be invoked if the object pionted at doesn't have
the virtual method implemented.
 
Not true, I tried this and g returns "A".

Then your compiler is broken. Compile and run this program, just using
csc, and see what happens:

using System;

class A
{
public virtual string a() { return "A";}
}

class B:A
{
public override string a() { return "B";}
}

class C:B
{
public override string a() { return "C";}
}

class D:C
{
}

class Test
{
static void Main()
{
A a = new D();

Console.WriteLine (a.a());
}
}
 
Back
Top