Search code examples
vb.netenumsnullableequality

Compare Nullable Enum (vb)


I have written the following code to do this but is there a more elegant way?

I have 2 nullable Enum's. I want to compare them to each other, where one or both can be null. I have to test separately for equality and test for the null condition. Is there a better way?

Private Class a
    Public Enum MyColour
        Red
        Blue
    End Enum
    Public Property OriginalColour As MyColour?
    Public Property NewColour As MyColour?

    Public ReadOnly Property HasColourChanged As Boolean
        Get
            If (OriginalColour.HasValue And NewColour.HasValue) Then  'Both have values so test
                'Test if the values are the same
                If OriginalColour.Value = NewColour.Value Then
                    Return False
                Else
                    Return True
                End If
            End If

            'Either one or both values are null
            If OriginalColour.HasValue Xor NewColour.HasValue Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property
End Class

Solution

  • You can use the Nullable.Equals method. Keeps things nice and simple.

    Public ReadOnly Property HasColourChanged As Boolean
        Get
            Return Not Nullable.Equals(OriginalColour, NewColour)
        End Get
    End Property