Reputation: 12226
I have ToString()
defined in a parent class in a way that applies to nearly all of its descendent classes, which usually involves calling a property called Name. This property is redefined in the child classes.
However, this doesn't work because the Name property from the parent class is always used, even when I redefine it in the descendent class.
Here is an example:
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
Bar n = new Bar();
Console.WriteLine(n);
Console.ReadLine();
}
}
class Foo
{
public override string ToString()
{
return MyName;
}
public string MyName { get { return "foo"; }}
}
class Bar : Foo
{
public new string MyName { get { return "bar"; }}
}
}
The output of this example is foo
but I want it to be bar
.
What am I doing wrong? Or am I just misunderstanding a fundamental aspect of inheritance in C#?
Upvotes: 1
Views: 66