Question

I have a class Like

public class Person
{
    public string Name{ get; set; }
    public string Address{ get; set; }
    public List<Person> Children{ get; set; }
}

Here I have a property Children List.

and Now I am creating an array of this class instances by using type initializer like

var persons = new []{
    new Person{ Name="Some Name", Address = "Some Address" },
    new Person{ Name="Some Name 2", Address = "Some Address 2", Children = new List<Person>{
          new Person { Name = "Some Name 3",
                ** Address = <here I want its parent Address>  "Some Address 2" **}
       }
    }
};

So, My Problem is that I am creating an object of Person where I assign its Address property and now I want this property value to assign its children, but I am not finding a way to get the its parent like we just do by this keyword to get a class member in its definition.

Was it helpful?

Solution

There is no easy way provided by C# to do this. The parent-child relationship between the Person object and its children above is not enforced or provided by the language. The easiest way to solve the problem above is store the address in a variable and reference it.

string address = "Some Address 2";
var persons = new []{
    new Person{ Name="Some Name", Address = "Some Address" },
    new Person{ Name="Some Name 2", Address = address, 
        Children = new List<Person>{
              new Person { Name = "Some Name 3", address }
       }
    }
};

Alternatively, a Person object could set the address of any children to itself in a data-binding like arrangement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top