Context
- I have a
List<T>
of typeQuestion
. - Class
Question
, in turn, contains aList<Answer>
. - Class
Answer
has 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?
}
}
};