Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between Dictionary.Keys.Contains(key) and Dictionary.ContainsKey(key) [duplicate]

Tags:

c#

.net

Suppose:

Dictionary<Guid, MyClass> dict;

Is there any difference between

dict.Keys.Contains(key)

and

dict.ContainsKey(key)

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

like image 219
Hong Avatar asked Dec 19 '22 04:12

Hong


1 Answers

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

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

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

This method is part of KeyCollection class. Its dictionary field refers to the Dictionary object that owns the KeyCollection returned by Keys property.

like image 53
Sergey Kalinichenko Avatar answered May 26 '23 20:05

Sergey Kalinichenko