0

I found this example in another question. I was wonder wat purpose was served by the method Question(). It seems like when the Question object is created the Answer property is created as a List object of Answer[s].

This is the first time I have seen this technique, as a new programmer, what is the benefit from this pattern?

public class Question
{
   public Question()
   {
      this.Answers = new List<Answer>();
   }
   public int QuestionId { get; set; }
   public string Title { get; set; }
   public virtual ICollection<Answer> Answers { get; set; }

}

public class Answer
{
   public int AnswerId { get; set; }
   public string Text { get; set; }
}
Community
  • 1
  • 1
Barry MSIH
  • 3,525
  • 5
  • 32
  • 53

2 Answers2

0

I find this pattern useful to make consumption of the object easier. I.e., by creating the Answers list in the constructor, it is ensured that Answers is never null. It just makes it easier to work with the Question object. So, in code that consumes a question object, you can do this

foreach (Answer in question.Answers)
{
    ...
}

without having to first check if questions.Answers is null:

if (question.Answers != null)
{
   foreach (Answer in question.Answers)
   {
       ...
   }
}
Ana M
  • 467
  • 5
  • 13
0

I assume that this technique is used when you for some reason don't want to use lazy loading. When lazy loading is enabled and POCO classes are properly configured, you do not have to initialize you collection navigation property, it will be automatically populated after you 'touch' it for the first time.

RX_DID_RX
  • 4,113
  • 4
  • 17
  • 27