C# auto update variable in dictionary is possible?

Example I Using This Code but this code not changing value in the dictionary auto update value in dictionary on changed is possible ?

Dictionary<string, string> dic = new Dictionary<string, string>();
private void DoWork()
{
        dic.Add("data", "example1");
        dic.Add("data2", "example2");
        if(dic.TryGetValue("data",out string c))
        {
            c = "Value Changed Good";
        }

        foreach (string s in dic.Values)
        {
            Console.WriteLine(s);
        }
}

Example this code output is a

example1
example2

but value not changed example if value changed this output changed with this

Value Changed Good
example2

Answer

If you want to update collection items, you should probably use the solution provided in Oliver’s answer. That’s the most straightforward way to go, I guess.

If you want to avoid a duplicate lookup when updating collection values in your for-loop, you could consider wrapping your collection values in a wrapper object. It could look something like this:

class Wrapper
{
    public string Value { get; set; }
}

Dictionary<string, Wrapper> dic = new Dictionary<string, Wrapper>();

private void DoWork()
{
    dic.Add("data", new Wrapper { Value = "example1" });
    dic.Add("data2", new Wrapper { Value = "example2" });

    if (dic.TryGetValue("data", out Wrapper c))
    {
        c.Value = "Value Changed Good";
    }

    foreach (Wrapper s in dic.Values)
    {
        Console.WriteLine(s.Value);
    }
}

But mind that this will also introduce additional overhead (especially when reading values from the dictionary). And it will probably make your code somewhat harder to read and understand as well.