Search code examples
c#treenode

C#: how can I derive the value of new attribute from the base class attribute?


I would like to add an attribute to treenode object.

I want the new attribute value(i.e. key) is derived from Treenode.Fullpath.

How can I implement it?

class ItemNode:TreeNode
{
    internal string key  { get; set; } = base.FullPath.split("\\")[1]; //Error
} 

Solution

  • That value can't be computed at the moment that the field is being initialized. It's too early. The object is still being constructed and the compiler can't be sure that the base portion is in a valid state, so access to its data is not allowed.

    I would recommend you implement the property yourself so that you can control when the logic executes. Then you could load it whenever you want. For example, a simple lazy load could work like this:

    class ItemNode:TreeNode
    {
        internal private string _key = null;
    
        internal public string Key
        {
            get
            {
                if (_key == null) _key = base.FullPath.split("\\")[1];
                return _key;
            }
            set 
            {
                _key = value;
            }
         }
    }