xander xander - 1 month ago 9
C# Question

Passing a "reference" to Dictionary element?

So I have:

ConcurrentDictionary<string, int> dict;


I want to pass a reference to one of its elements, suppose
dict["x"]
to a method, and allow that method to change/set that element. Is it possible to do exactly that, or do I have to pass the dictionary itself? Also, is it possible to do so even if the element does not exist as a key in the dictionary? Or does it already has to be a valid key contained in the dictionary?

Answer

Yes, by using a delegate. This delegate can be called from within the changing function. The delegate will then change or set the key/value inside the dictionary.

void DoChangeMyElement<T>(Action<T> changeIt)
{
    changeIt(123);
}

You can call this method with:

ConcurrentDictionary<string, int> dict = new ...;
DoChangeMyElement(value => dict["X"] = value);
Comments