I currently have a Match struct which contains a list of Blocks.
public struct Match{
public List<Block> blocks;
}
When I try to create a new Match (in this case, called matchData) and add Blocks to its Block list, my compiler outputs:
Use of unassigned local variable 'matchData'
I tried initializing the list by doing this:
public struct Match{
public List<Block> blocks = new List<Block>();
}
which results in the following error:
Structs cannot have instance field initializers
So how should I initialize my Match struct? Do I have to make a constructor?
From MSDN:
It is also an error to initialize an instance field in a struct body. You can initialize struct members only by using a parameterized constructor or by accessing the members individually after the struct is declared. Any private or otherwise inaccessible members can be initialized only in a constructor.
http://msdn.microsoft.com/en-us/library/0taef578.aspx
So you can initialize the list in a parameterized constructor like so:
public struct Match{
public List<Block> blocks;
public Match(List<Block> blocks)
{
this.blocks = blocks;
}
}
Or set it from the outside:
Match m = new Match();
m.blocks = new List<Block>();
As a side note, you probably would be better off using a class instead of a struct here. Your use doesn't seem to fit the typical use-case, as indicated here: http://msdn.microsoft.com/en-us/library/ah19swz4.aspx
You were getting "Use of unassigned local variable 'matchData'" because you didn't call new Match()
:
Match matchData;
matchData.blocks = new List<Block>(); // error!
But:
Match matchData = new Match();
matchData.blocks = new List<Block>(); // fine!
Structs have an implicit parameterless constructor which initializes all fields to default values.
However: You should be using class
instead of struct
, unless you understand exactly how structs work in C#. Do not just use struct because it's "lighter" than a class.
In particular, your Block
struct is mutable, which makes for a bad time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With