Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# take value from overridden property instead of the overriding property?

I would suspect the code below to output:

(I am a SmartForm object and using the method in SmartForm).xml

instead, however, it outputs:

(I am a SmartForm object and using the method in Item).xml

Why is that? How can I force C# to take the value from the overriding property? That is why I am overriding the property.

using System;

namespace TestInhersdk234
{
    public class Program
    {
        static void Main(string[] args)
        {
            SmartForm smartForm = new SmartForm();
            Console.ReadLine();
        }
    }

    public class SmartForm : Item
    {
        public SmartForm()
        {
            Console.WriteLine(FullXmlDataStorePathAndFileName);
        }

        public new string GetItemTypeIdCode
        {
            get
            {
                return String.Format("(I am a {0} object and using the method in SmartForm)", this.GetType().Name);
            }
        }
    }

    public class Item
    {
        public string FullXmlDataStorePathAndFileName
        {
            get
            {
                return GetItemTypeIdCode + ".xml";
            }
        }

        public string GetItemTypeIdCode
        {
            get
            {
                return String.Format("(I am a {0} object and using the method in Item)", this.GetType().Name);
            }
        }
    }
}
like image 712
Edward Tanguay Avatar asked Nov 30 '22 07:11

Edward Tanguay


1 Answers

You're not actually overriding. You're hiding. To override:

class MyBase
{
    public virtual void foo() {}
}

class MyClass : MyBase
{
    public override void foo() {}
}
like image 106
Jon B Avatar answered Dec 05 '22 13:12

Jon B