Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a list within a struct

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?

like image 435
TheYokai Avatar asked Jan 11 '23 10:01

TheYokai


2 Answers

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

like image 101
Mike Hixson Avatar answered Jan 12 '23 22:01

Mike Hixson


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.

like image 41
Blorgbeard Avatar answered Jan 12 '23 22:01

Blorgbeard