Home
VB.NET
Dictionary ContainsKey Example (ContainsValue)
Updated Oct 27, 2023
Dot Net Perls
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.
Dictionary TryGetValue
Dictionary
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.
Boolean
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 Module
tan 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 27, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen