Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialize members of a struct without using a constructor?

Tags:

c#

struct

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:

  1. Initialize both properties when I create an instance of MonthData
  2. Use a class instead of a struct
  3. Create a constructor with a parameter and use that
  4. 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.

like image 710
Mike Christensen Avatar asked Nov 16 '11 20:11

Mike Christensen


2 Answers

You're using reference types (List<T>) in your struct anyway, thus the usage of a struct as value type wouldn't make any sense to me. I'd just go with a class.

like image 121
Dennis Traub Avatar answered Oct 20 '22 17:10

Dennis Traub


You ought to use a class instead. From MSDN:

In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

like image 7
Daniel Mann Avatar answered Oct 20 '22 16:10

Daniel Mann