简体   繁体   中英

Check for null value for value types in VB.NET

I have a KeyValuePair(Of TKey,TValue) and I want to check if it is null or not:

Dim dictionary = new Dictionary(Of Tkey,TValue)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = *someValue*)

If keyValuePair isNot Nothing Then 'not valid because keyValuePair is a value type
    ....
End If

If keyValuePair <> Nothing Then 'not valid because operator <> does not defined for KeyValuePair(of TKey,TValue)
   ...
End If

How can I check if keyValuePair is null or not?

KeyValuePair(Of TKey, TValue) is a struct(Structure), it has default value which you can compare to.

Dim dictionary As New Dictionary(Of Integer, string)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = 2)

Dim defaultValue AS KeyValuePair(Of Integer, string) = Nothing

If keyValuePair.Equals(defaultValue) Then
    ' Not found
Else
    ' Found
End If

Nothing represents default value of the corresponding type.

But because you are searching Dictionary for a key, you can use TryGetValue instead

Dim dictionary As New Dictionary(Of Integer, string)
Dim value As String

If dictionary.TryGetValue(2, value) Then
    ' Found
Else
    ' Not found
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM