Search code examples
c#.netarraysvb.netcode-translation

Translate this C# comparison to VB.NET


I'm trying to translate a comparison between two Nullable(Of Byte) objects:

    public byte?[] header { get; private set; }

    public override bool Equals(object other)
    {
        // ... more code to translate
        if (this.header != otherType.header) return false;
        // ... more code to translate
    }

An online code translator gives me this equivalent:

    Private m_header As Nullable(Of Byte)()
    Public Property header() As Nullable(Of Byte)()
        Get
            Return m_header
        End Get
        Private Set(value As Nullable(Of Byte)())
            m_header = value
        End Set
    End Property

    Public Overrides Function Equals(other As Object) As Boolean

        ' ... more code translated
        If Me.header <> otherType.header Then
            Return False
        End If
        ' ... more code translated

    End Function

But I get this exception:

Operator '<>' is not defined for types '1-dimensional array of Byte?' and '1-dimensional array of Byte?'. Use 'Is' operator to compare two reference types.

Then, as the detail of the exception says, I would like to know if this should be the proper translation 'cause I'm not totally sure:

If Not Me.header Is otherType.header Then
    Return False
End If

Solution

  • You could use the null-coalescing operator to treat a null-byte as 0:

    Public Overrides Function Equals(other As Object) As Boolean
        ' ... '
        Dim otherType = TryCast(other, ActualType)
        If otherType Is Nothing Then Return False
        If If(Me.header, 0) <> If(otherType.header, 0) Then
            Return False
        End If
        ' ... '
    End Function
    

    Here is an approach which checks if both nullable-arrays are equal:

    If header Is Nothing AndAlso otherType.header Is Nothing Then
        Return True
    ElseIf Object.ReferenceEquals(header, otherType.header) Then
        Return True
    ElseIf header Is Nothing OrElse otherType.header Is Nothing Then
        Return False
    Else
        Return header.SequenceEqual(otherType.header)
    End If