-2

I have a class with a dictionary defined as a private member :

    Dictionary<int, (string, string)> arenaIdToSetAndNumber = new Dictionary<int, (string, string)>()
    {
        { 70506, ("c16", "337") },
        { 70507, ("c16", "340") },
        { 70508, ("c16", "343") },
        { 70509, ("c16", "346") },
        { 70510, ("c16", "349") },
    };

While debugging, I get to an item corresponding to key 70506, I see this with 2 watches:

y

I try doing var test = arenaIdToSetAndNumber[c.grpId].Item1 and test is set to null just as seen in the second watch! I don't understand why

Bruno
  • 4,685
  • 7
  • 54
  • 105
  • 1
    NEVER post images of code, errors or output! https://stackoverflow.com/help/how-to-ask – Rob Jul 29 '19 at 12:45

2 Answers2

0

The debugger and the watcher are not able to infer what is Item1 from the indexer operator [], thus will give you null in the watch. But once you run the code, it will just work fine for reading purpose. For writing purpose instead, you need to take out the whole tuple, edit it and reinsert in the dictionary:

static void Main(string[] args)
    {
        Dictionary<int, (string, string)> arenaIdToSetAndNumber = new Dictionary<int, (string, string)>()
        {
            { 70506, ("c16", "337") },
            { 70507, ("c16", "340") },
            { 70508, ("c16", "343") },
            { 70509, ("c16", "346") },
            { 70510, ("c16", "349") },
        };

        var myTuple = arenaIdToSetAndNumber[70509];
        myTuple.Item1 = "c18";
        arenaIdToSetAndNumber[70509] = myTuple;
        //System.Console.WriteLine(arenaIdToSetAndNumber[70509].Item1); // This prints c18
    }

Otherwise, in one line, just recreate the whole tuple:

arenaIdToSetAndNumber[70509] = ("c18", arenaIdToSetAndNumber[70509].Item2);

All of this because the ValueTuple is a struct. Similar question here

Fabio M.
  • 296
  • 2
  • 8
0

This does not use tuples but solves your problem. Since you want to read the values create an immutable class, use properties to retrive the values.

public class Contents
{
    private readonly string leftValue;
    private readonly string rightValue;

    public Contents(string aLeftValue, string aRightValue)
    {
        leftValue = aLeftValue;
        rightValue = aRightValue;
    }

    public string LeftValue => leftValue;
    public string RightValue => rightValue;       
}

Modify your code to use the new class.

 Dictionary<int, Contents> arenaIdToSetAndNumber = new Dictionary<int, Contents>()
        {
            { 70506, new Contents("c16", "337") },
            { 70507, new Contents("c16", "340") },
            { 70508, new Contents("c16", "343") },
            { 70509, new Contents("c16", "346") },
            { 70510, new Contents("c16", "349") },
        };

And you can test it with this.

  var content = arenaIdToSetAndNumber[70506];
  string leftValue = content.LeftValue;
  string rightValue = content.RightValue;

Hope this solves your problem.