0

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.

1 Answers1

0

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 */ }
    // ...
  }
}
SNBS
  • 671
  • 2
  • 22
  • So It cant be done at the moment? Its a bit verbose if you have a hierarchy of many nested classes. In your answer the Ids of all classes would would the same, so I would need to create different variables for each nested class at the global level. – Joseph Hutton Dec 17 '22 at 19:17
  • @JosephHutton Yes, that's true. But the compiler is fair here: you can't use properties of the object being created, because you can only use initialized objects (and when the code in object initializer is performed, the object isn't created yet). – SNBS Dec 17 '22 at 20:02