简体   繁体   中英

Check if Class is Nothing, or Structure is default value, using a single condition

I've written my own method for programmatically selecting an item in a ComboBox:

Function SelectItem(ByVal item As Object, ByVal comboBox As ComboBox) As Boolean
  If Not comboBox.Items.Contains(item) Then
    comboBox.Items.Add(item)
  End If

  comboBox.SelectedItem = item

  Return True
End Function

The "item" parameter can be any Class , like a String, but it can also be a (custom) Structure .

When the parameter is Nothing (or the default structure value), this method should return False . How do I achieve this condition?

' This will not work, because "=" can't be used with classes
If item = Nothing Then Return False

' Won't work either, because "Is" is always False with structures
If item Is Nothing Then Return False

' Obviously this would never work
If item.Equals(Nothing) Then Return False

' Tried this too, but no luck :(
If Nothing.Equals(item) Then Return False

How should I handle this condition? I could use Try ... Catch , but I know there must be a better way.

This function does the trick:

Public Function IsNullOrDefaultValue(item As Object) As Boolean
    Return item Is Nothing OrElse (item.GetType.IsValueType Andalso item = Nothing)
End Function

Test results by passing variable:

Dim emptyValue As Integer = 0          ==> True
Dim emptyDate As DateTime = Nothing    ==> True
Dim emptyClass As String = Nothing     ==> True
Dim emptyStringValue As String = ""    ==> False
Dim stringValue As String = "aa"       ==> False
Dim intValue As Integer = 1            ==> False

I wasn't quite sure in which conditions you wanted to return True/False, but this code shows how you can check the type and compare it to a specific value. This way you're not trying to compare it to a value if it's the wrong type.

If (TypeOf myVar is MyClass andalso myVar isnot nothing) _
    OrElse TypeOf myVar is MyStructure AndAlso myVar = MyStructure.DefaultValue) Then
    ...
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