ContainsKey. This VB.NET Dictionary function is used to determine whether a key exists within a Dictionary. It returns True or False based on whether the key exists.
A limitation of ContainsKey is that it does not return the value. To combine both a key-testing function with a value-getting function, consider TryGetValue.
Example. To test the result of ContainsKey on Dictionary, we must first create a sample Dictionary. We specify String keys to mean colors, and Integer values.
Part 1 We use ContainsKey with the argument "tan" which is found in the Dictionary. ContainsKey returns True here.
Part 2 Meanwhile "blue" is not found in the Dictionary, so ContainsKey returns False.
Part 3 Here we use ContainsValue, which searches the values in the Dictionary and determines whether the argument is present as a value.
Module Module1
Sub Main()
Dim colors = New Dictionary(Of String, Integer)
colors.Add("tan", 100)
colors.Add("lavender", 200)
colors.Add("ochre", 300)
' Part 1: look up value that exists with ContainsKey.
If colors.ContainsKey("tan")
Console.WriteLine("tan was found!")
End If
' Part 2: look up missing key.
If colors.ContainsKey("blue")
' Not reached.
Else
Console.WriteLine("blue was not found...")
End If
' Part 3: use ContainsValue.
If colors.ContainsValue(200)
Console.WriteLine("value 200 was found!")
End If
End Sub
End Moduletan was found!
blue was not found...
value 200 was found!
Performance. The Dictionary in .NET is highly-optimized for key lookup, so ContainsKey will be fast. But values are not hashed, so they cannot be searched quickly.
Warning Avoid using ContainsValue in code that must be fast. Consider creating a separate Dictionary where the values are keys.
Summary. Many programs written in VB.NET that use the Dictionary collection will use ContainsKey. Sometimes, using TryGetValue can be better if avoids a second lookup.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.