1

I have a base class that has a property and a method that uses that property. I have a class that inherits that base class and has its own implementation of the base class's property that is explicitly hidden using the New modifier. In the base class' method, is there a good way to use the inherited class' property instead of the base's implementation?

class Program
{
    public class MyBase
    {
        public string MyProperty { get { return "Base"; } }

        public string MyBaseMethod()
        {
            return MyProperty;
        }
    }

    public class MyInherited : MyBase
    {
        public new string MyProperty { get { return "Inherited"; } }
    }

    static void Main(string[] args)
    {
        List<MyBase> test = new List<MyBase>();
        test.Add(new MyBase());
        test.Add(new MyInherited());

        foreach (MyBase item in test)
        {
            Console.WriteLine(item.MyBaseMethod());
        }
    }
}

In the example, the output is: Base Base

Current workaround:

    ...
    public class MyBase
    {
        public string MyProperty { get { return "Base"; } }
        public string MyBaseMethod()
        {
            if (this is MyInherited)
            {
                return baseMethod(((MyInherited)this).MyProperty);
            }
            else
            {
                return baseMethod(MyProperty);
            }
        }

        private string baseMethod(string input)
        {
            return input;
        }
    }
    ...

Is there a better way to do this? I'd rather not have to do explicit type casts.

rae1
  • 6,066
  • 4
  • 27
  • 48
yourbuddypal
  • 543
  • 6
  • 18

3 Answers3

8

Hiding a member with the new keyword should generally be avoided. Instead make the base class' property virtual and override it in the descending class. The MyBaseMethod will automatically use this overridden property in inheriting classes.

public class MyBase
{
    public virtual string MyProperty { get { return "Base"; } }

    public string MyBaseMethod()
    {
        return MyProperty;
    }
}

public class MyInherited : MyBase
{
    public override string MyProperty { get { return "Inherited"; } }
}

var inherited = new MyInherited();
Console.WriteLine(inherited.MyBaseMethod()); // ==> "Inherited"

See this interesting post related to the new keyword: Why do we need the new keyword and why is the default behavior to hide and not override?

Community
  • 1
  • 1
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
3

Make the property virtual, not sealed, and override it, rather than shadowing it. Then all uses of the property will use the most derived implementation of it.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

There is no such way. If you do new (which is early binding), you have to do explicit casts. The only solution is to make the property virtual. Then you can override it (using the override modifier). This is late binding.

Robetto
  • 739
  • 7
  • 20