HichemSeeSharp
HichemSeeSharp

Reputation: 3318

How to instantiate a property with its parent instance at declare time

Here's my code:

 var Operations = new List<Operation>
 {
     new Operation
     {
         Date = DateTime.Now,
         OperationId = 0,
         OperationType = OperationType.Entry,
         OperationVehicles = new List<OperationVehicle>
         {
             new OperationVehicle { Vehicle = vehicle},
         }
     },
     new Operation
     {
         Date = DateTime.Now.AddDays(2),
         OperationId = 1,
         OperationType = OperationType.Exit,
         OperationVehicles = new List<OperationVehicle>
         {
             new OperationVehicle { Vehicle = vehicle, /* Operation = ???*/},
         }
     }
 };

OperationVehicle class has a virtual public property of type Operation that I want to instantiate it with its parent Operation instance at this stage. Well, I think at this time the Operation may be not created yet. Is there a way to do this in C# or do I have to do classic affectation ?

Upvotes: 3

Views: 105

Answers (1)

keyboardP
keyboardP

Reputation: 69372

From Section 7.6.10.2 in the C# Language spec (emphasis mine).

An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and an expression or an object initializer or collection initializer. It is an error for an object initializer to include more than one member initializer for the same field or property. It is not possible for the object initializer to refer to the newly created object it is initializing.

If I understand your question correctly then it's not possible to refer to the new object within the object initialization so it's not possible to do what you're trying as vehicle is not accessible at this point.

Upvotes: 1

Related Questions