-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Proposal] Add overload for Dictionary.TrytGetValue() to get ref value types. #3217
Comments
I don't think you proposed API would work. if (dict.TryGetValue(key, ref int value)) {
dict.Remove(key);
value += i;
} else {
dict[key] = i;
} |
Would be a .NET library proposal rather than a C# specific one; here's one for you 😉 |
The proposed API wouldn't work, because that's not how For that, you need @dotjpg3141 You're right that this feature would be dangerous, the proposal I linked to above resolves that by "hiding" the method in a different class in an obscure namespace, in an attempt to ensure that you only use it if you understand those limitations. |
There's a DictionarySlim in experimental collections that provides something similar to what you want through |
That's right, that's not how ref paramters work. Total brain fart on my part! |
Eg:
Idea here is to avoid a currently necessary second access for value types that exists in a number of scenarios.
For example, say you have a dictionary of type <string, int> and an int i which you either want to add to an existing value, or assign as a new item if a key does not already exist.
Currently, this looks like:
If the key exists we need to perform a second dictionary access, which isn't ideal. However, if we can use the ref keyword on the second TryGetValue parameter we're able to avoid the second access altogether. Eg:
The text was updated successfully, but these errors were encountered: