Question

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
Was it helpful?

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

OTHER TIPS

The error message is telling you exactly what to do:

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

The Is operator in VB.NET makes reference comparisons, exactly like == does in C# for reference types that have not overridden it (byte[] is such a type).

Looks like the converter has added in the "Offset" for some reason known only to its developers (or perhaps not even them) it should work as you put it at the end of your post.

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

Or alternatively (I think this is a bit more readable):

If Me.header IsNot otherType.header Then
    Return False
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top