vb.netkey-valuevalue-typereference-type

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?


Solution

  • 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