Search code examples
c#classpropertiesparent

Access upper class property for List<T> in T class C#


There are my classes:

public class myClass1
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    private void MyMethod()
    {
        int ParentClass_CodeProperty = ???
    }
}

How to access (Code property) in upper (or Parent) class ?

example :

string ParentClass_CodeProperty = this.Parent.GetType().GetProperty("Code").GetValue(a, null).ToString()

Solution

  • One thing you can do is modify your MyItem class to have a ParentClassCode property, and let this get set through the constructor:

    public class MyItem
    {
        public int ParentClassCode { get; set; }
    
        public MyItem(int parentClassCode)
        {
            ParentClassCode = parentClassCode;
        }
        private void MyMethod()
        {
            // Now we can refer to ParentClassCode
        }
    }
    

    Then you would set the parent class code on creation of a new MyItem:

    MyClass1 class1 = new MyClass1();
    class1.Code = 42;
    class1.Items.Add(new MyItem(class1.Code));
    

    Another way to do this, without using the constructor, would be to create a method on the containing class that should be used to add items to the list, and in that AddItem method, set the property:

    public class MyClass1
    {
        public int Code { get; set; }
        public List<MyItem> Items { get; set; }
    
        public void AddItem(MyItem item)
        {
            if (item == null) throw new ArgumentNullException();
            item.ParentClassCode = Code;
            Items.Add(item);
        }
    }
    

    Of course this means there's more work to do to prevent users from bypassing your AddItem method and calling MyClass1.Items.Add(item);, but you get the idea.