Is there a difference between Dictionary.Keys.Contains (key) and Dictionary.ContainsKey (key)

Let's pretend that:

Dictionary<Guid, MyClass> dict;

Is there any difference between

dict.Keys.Contains(key)

and

dict.ContainsKey(key)

I thought there was no difference, but now I'm not sure.

+4
source share
3 answers

These two methods are guaranteed to return the same value of true/ false.

According to the reference implementation , dict.Keys.Contains(key)delegates dict.ContainsKey(key):

bool ICollection<TKey>.Contains(TKey item){
    return dictionary.ContainsKey(item);
}

This method is part of the class KeyCollection. Its field dictionaryrefers to the object dictionaryto which KeyCollectionit returned the property Keys.

+8
source

, , .

Dictionary.Keys . , , .

, .

+2

.

dict.ContainsKey(key) .

dict.Keys.Contains(key), . IEnumerable<TKey>, () . , , .

+1
source

Source: https://habr.com/ru/post/1684997/


All Articles