ScottishTapWater
ScottishTapWater

Reputation: 4786

Create Dictionary of Custom Struct and Access Properties in C#

I've created a struct defined below:

    public struct Piece
{
    string pieceType;
    string pCode;
    bool dead;
    bool highlighted;
    bool specialUsed;
    bool moved;
    Material defaultMaterial;
}

and in a separate subroutine have created a dictionary which will hold entries of this type:

Dictionary<string, Piece> pieceDict;

I'm attempting to populate it using a foreach loop like so:

            GameObject[] pieces = GameObject.FindGameObjectsWithTag("Piece");
        foreach (GameObject piece in pieces)
            {
            string pCode = GetPieceCode(piece);
            pieceDict.Add(pCode, new Piece());
            pieceDict[pCode].pCode = pCode;
            //More properties once I get this working will go here.
            }

However, it would appear that something is going wrong as it will not allow me to access the individual properties of the new entry. Getting this error:

 Cannot modify the return value of 'Dictionary<string, Piece>.this[string]' because it is not a variable

I have looked at the documentation and can't work out where I'm going wrong, so any help would be appreciated!

I'm using the UnityEngine.

Upvotes: 2

Views: 1757

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

Structs are value types, when you pass a struct, it creates a copy of the struct. This is especially a problem with mutable structs since when you pass the struct to a method (or get it out of a property) the struct is copied by value and then you are modifying the copy, not the original.

The fix is to avoid mutable structs and to use a class instead. Only use structs where the value (of all its fields) is fixed during construction.

Edit

To expand on this a little bit, we can examine the line:

pieceDict[pCode].pCode = pCode;

What is happening here is that the first part, pieceDict[pCode] returns a copy of the value (in the case of a value type), which is then operated on by the .pCode part, which you assign it to pCode, but because you are working on a copy, and not what is stored in the dictionary, it will not be saved. The compiler is smart enough to notice that you are trying to assign to it and that it will be thrown away anyway, so it gives you the error.

In my opinion the error could be better worded, something like "assignment to a copy of a value type does not result in an assignment of the underlying value", because as a new-ish programmer when it says that the assignment fails because its not a variable is a little confusing. The dictionary is a variable, the item that went in is a variable, so its hard to understand why the value is not a variable.

Upvotes: 5

Related Questions