Should I always use Dictionary.TryGetValue even if I all want to do is add/replace values?

StackOverflow https://stackoverflow.com/questions/16195674

  •  11-04-2022
  •  | 
  •  

문제

I've been using TryGetValue to add/replace data in my dictionaries. Just to make the distinction between adding new vs. replacing old, I use both [] and .Add(). This leads to code like this, if I am not actually doing anything with the retrieved value:

private Dictionary<Foo, Bar> dictionary = new Dictionary<Foo, Bar>();

public void Update(Foo foo)
{
    Bar bar;
    if (dictionary.TryGetValue(foo, out bar)
    {
        dictionary [foo] = bar;
    }
    else
    {
        dictionary .Add(foo, bar);
    }
}

If I am not actually doing anything with the retrieved value, is there a reason why I shouldn't replace the above code with this?:

public void Update(Foo foo)
{
    dictionary[foo] = bar;
}

Thank you in advance.

도움이 되었습니까?

해결책

You should use the simpler code.
It will be faster in all cases. (one hash lookup vs. two)

More importantly, it's simpler.

다른 팁

No, there is no reason to not use the shorter code.
In fact, you really should use it, as it is much simpler and we all know:
Simpler code means less errors.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top