Home > other >  Multiple nested object initialisers with recursive constructor properties
Multiple nested object initialisers with recursive constructor properties

Time:12-18

Is there a way to pass default/constructed property vales in object initializers - to the constructors of nested object initializers?

e.g.

take these 3 classes Car, Part, Tool

Car 
{
  public Guid ManufacturerId { get; set; }
  public Guid CarId { get; set; }
  public List<Part> Parts { get; set; }
  //.. name property etc


  public Car(Guid manufacturerId)
  {
    ManufacturerId = manufacturerId;
    CarId = Guid.NewGuid();
    Parts = new List<Part>();
  }
}
Part
{
  public Guid PartId { get; set; }
  public Guid CarId { get; set; }
  public List<Tool> Tools { get; set; }
  //.. name property etc


  public Part(Guid carId)
  {
    CarId = carId;
    PartId = Guid.NewGuid();
    Tools = new List<Tool>();
  }
}
Tools
{
  public Guid ToolId { get; set; }
  public Guid PartId { get; set; }
  //.. name property etc


  public Tools(Guid partId)
  {
    PartId = partId;
    ToolId = Guid.NewGuid();    
  } 
}

If I create an instance of the car class with an object initializer, is it possible to pass the Id property created in the parent car class to a child Part object initializer's constructor parameter? This would be especially useful where the constructor values of list property classes cannot be resolved in the parent classes constructor when the list class is first constructed.

e.g.

var car = new Car(Guid.NewGuid())
{
  Parts = new List<Part>()
    {
      new Part(...insert constructed car.CarId here...) 
        {...part object initializer etc...},

      new Part(...insert constructed car.CarId here...)
        {...part object initializer etc... },
    }
};

I want to be able to construct an object like this with list properties in one statement without resorting to defining the vales of each constructor parameter at the global level.

CodePudding user response:

In an object initializer, you can't access properties of the object being created, but you can create a variable containing the car ID and use it:

var id = Guid.NewGuid();

var car = new Car(id)
{
  Parts = new List<Part>()
  {
    new Part(id)
    { /* Initialize the part */ },
    new Part(id)
    { /* Initialize the part */ }
    // ...
  }
}
  • Related