relaxxx
relaxxx

Reputation: 7834

Prevent double lookup of the same element in Dictionary

I know there is no reference to "struct" variable in C#, but this is the case where it would come handy

    Dictionary<int, int> d = new Dictionary<int, int>();

    d.Add(1, 1);

    ++d[1];
    ++d[1];

how can I perform 2 operations (increment in this case) on the same element without using operator[] twice (to prevent double lookup)?

Upvotes: 2

Views: 373

Answers (1)

Servy
Servy

Reputation: 203844

You can create a mutable reference type that wraps another value, in this case an immutable value type, allowing the value of the wrapper to be mutated:

public class Wrapper<T>
{
    public T Value { get; set; }
}

This lets you write:

Dictionary<int, Wrapper<int>> d = new Dictionary<int, Wrapper<int>>();

d.Add(1, new Wrapper<int>(){Value = 1});

var wrapper = d[1];
wrapper.Value++;
wrapper.Value++;

Upvotes: 4

Related Questions