Why return false?

  • Thread starter Thread starter yxq
  • Start date Start date
Y

yxq

In VB2005.

Dim a() As Object = {10, 4}
Dim b() As Byte = {10, 4}
MessageBox.Show(a.Equals(b))

Why return False, but not Ture?
Thank you
 
It compares the object not the array content. As this is two different
object, it returns false...
 
I don't know of an automated way, so you'll probably have to write your
own method (someone please correct me if I'm wrong). First check the
number of dimensions, as a one dimensional array can't equal a three
dimensional array, and then I would compare the lengths of both arrays.
Then you probably have to check each member of the array. By the way,
why do you need to check equality of arrays?

Thanks,

Seth Rowe
 
yxq,
In addition to the other comments.

2 problems:

First you are comparing a byte array to an object array, due to the fact you
have 2 distinct kinds of arrays they won't compare.

Second Object.Equals(Object) is a virtual (Overridable) method, allowing
types that have "identity" to override the method & offer an implementation.
Such types include Integer, String, DateTime...

Array does not override this method, as arrays don't have "identity" (in
select cases, such as yours, they may; but overall they don't). Instead
relying on the Object.Equals(Object) implementation.

Object.Equals(Object) itself does a Object.ReferenceEquals which compares
the two object references, not the content of said objects.

As Rowe suggests you will need to write your own function. I would consider
making such a function a Generic Function... However with having 2 distinct
types of arrays this makes a generic function problematic.

Here is a simply Generic ArrayEquals for VS 2005 (.NET 2.0):

Public Function ArrayEquals(Of T)(ByVal a() As T, ByVal b() As T) As
Boolean
If a.GetLowerBound(0) <> b.GetLowerBound(0) Then Return False
If a.GetUpperBound(0) <> b.GetUpperBound(0) Then Return False
Dim comparer As EqualityComparer(Of T) = EqualityComparer(Of
T).Default
For index As Integer = a.GetLowerBound(0) To a.GetUpperBound(0)
If Not comparer.Equals(a(index), b(index)) Then Return False
Next
Return True
End Function

It requires both parameters to be 1 dimension arrays.
 
Back
Top