longneck
longneck

Reputation: 12226

calling a dervied method from a parent class c#

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

Answers (1)

SLaks
SLaks

Reputation: 887395

That happens because ToString() is virtual.

Add the virtual keyword to your base property, and change new to override in the derived property.

Upvotes: 4

Related Questions