I have a struct that contains two lists:
struct MonthData
{
public List<DataRow> Frontline;
public List<DataRow> Leadership;
}
However, I want to initialize both when the struct is created. If I try:
struct MonthData
{
public List<DataRow> Frontline = new List<DataRow>();
public List<DataRow> Leadership = new List<DataRow>();
}
Then I get:
Error 23 'MonthData.Frontline': cannot have instance field initializers in structs
...
Since structs cannot have parameterless constructors, I can’t just set this in a constructor either. So far, I can only see the following options:
- Initialize both properties when I create an instance of MonthData
- Use a class instead of a struct
- Create a constructor with a parameter and use that
- Make getters and setters for the properties that initialize them
lazily.
What is the recommended approach for this? Right now, I’m thinking making this a class is the best idea.
You ought to use a class instead. From MSDN: