'Setting dictionary tuple values directly
Is it possible to do something similar to this: dictTupleTest[key].Item1 = toggle; in the following situation?
Dictionary<int, (bool, bool)> dictTupleTest = new Dictionary<int, (bool, bool)>();
var key = 3;
var toggle = false;
dictTupleTest.Add(key, (true, false));
//This works
dictTupleTest[key] = (toggle, dictTupleTest[key].Item2);
//While this gives an error
dictTupleTest[key].Item1 = toggle;
The error: Error CS1612: Cannot modify the return value of 'Dictionary<int, (bool, bool)>.this[int]' because it is not a variable.
Or is there a better way to do it?
Solution 1:[1]
Starting from .NET 6, it is possible to update a mutable value-type stored in a Dictionary<TKey,TValue> without doing more than one operations on the dictionary. The new API is the CollectionsMarshal.GetValueRefOrNullRef method:
Gets either a reference to a
TValuein theDictionary<TKey,TValue>, or a reference null if it does not exist in the dictionary.
It can be used like this:
using System.Runtime.InteropServices;
//...
CollectionsMarshal.GetValueRefOrNullRef(dictTupleTest, key).Item1 = toggle;
In case the key is not found in the dictionary, the above code will throw a NullReferenceException. For better control you can use a ref local like this:
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
//...
ref var entry = ref CollectionsMarshal.GetValueRefOrNullRef(dictTupleTest, key);
if (Unsafe.IsNullRef(ref entry)) throw new KeyNotFoundException();
entry.Item1 = toggle;
The CollectionsMarshal.GetValueRefOrNullRef API is non easily discoverable, and this is intentional:
This is niche unsafe API that 99% of .NET developers should not ever use. We do not want to encourage people to use it just because of they can.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Theodor Zoulias |
