Context
- I have a
List<T>of typeQuestion. - Class
Question, in turn, contains aList<Answer>. - Class
Answerhas a member calledpublic Question Question { get; set; }which stores the question of which the answer is for.
I'm using the collection initialization syntax to add a Question item to the list and object initialization to create a new Question. While doing so, I'm also creating new Answer objects using the object initialization syntax(nested).
Problem
How do I set the Question member of the inner Answer class to refer to the enclosing Question object? I know the point at which an Answer is created, the Question is not even fully initialized. But is there any way to obtain the outer Question instance so that I can set it to the inner Answer.
Code
private List<Question> questions = new()
{
new Question
{
Id = 1,
Text = "Test Question 1",
Difficulty = QuestionDifficulty.Easy,
Answers =
{
new Answer { Id = 1, Question = [?] },
new Answer { Id = 2, Question = [?] } // What should replace [?] here?
}
}
};
You can't do it in the collection/object initialiser, but I'd argue that you shouldn't do it there in the first place. It's quite error-prone to handwrite what the corresponding question for each answer should be. You might forget to do that sometimes too.
I suggest that you add a custom setter for the
Answersproperty inQuestionthat also sets the answer'sQuestionproperty:Then in the object initialiser, initialise the answers' list, rather than just adding to it:
This compiles to something like:
As you can see, the setter is called, and the answers'
Questionproperty will be set.