0

What i'm trying to do is create a new model that will have certain features:

public class GenericGoal
{
    public int _id { get; set; }
    public List<String> Type_of_Goal { get; set; }
    public DateTime Date { get; set; }
}

my quick and small question would be, how would I prepopulate the Type_of_goal field?

Mighty Badaboom
  • 5,609
  • 5
  • 27
  • 47

2 Answers2

0

You could give the property 'Type_of_Goal' an initial value, if you don't want to have to initialize it every time, or initialize it when no value is set to it.

public class GenericGoal
{
    public int _id { get; set; }
    public List<String> Type_of_Goal { get; set; } = new List<String>();
    public DateTime Date { get; set; }
}

If it is 'NullReferenceException' you are concerned about, check for null's before accessing the 'Type_of_Goal' property, as follow. Note the ? - Known as Null Propagation Operator

genericGoalInstance.Type_of_Goal?.Add("Good Goal");
monstertjie_za
  • 5,785
  • 6
  • 30
  • 63
0

You could use a constructor for this; could look like this example.

public class GenericGoal
{
    public int _id { get; set; }
    public List<String> Type_of_Goal { get; set; }
    public DateTime Date { get; set; }

    public GenericGoal()
    {
        Type_of_Goal = new List<String>();
    }
}

I recommend the initialisation in the constructor because in my opinion it's cleaner and better readable.

Mighty Badaboom
  • 5,609
  • 5
  • 27
  • 47