Array.IndexOf always returns -1

advertisements

This is my code.

Public Sub SomeFucntion(ByVal test As Short)
    SomeOtherFucntion(MyArray)

    If Array.IndexOf(MyArray, test) <> -1
       //....
    End If
End Sub

test return value 10.

But i am getting IndexOf value as -1.
Inside QuickWatch in VS 2005 when i put the value as 10 instead of test i am getting the correct index.

My array is single dimensional array which now has 2,5 and 10. Since its got 10 it should ideally return 2 as the index.


The problem might be caused by the fact that your array contains integers, but the value you are looking for is a short. Consider the following example:

Dim myArray As Integer() = {5}
Dim value As Short = 5
Console.WriteLine(Array.IndexOf(myArray, value))  ' Prints -1

If the array contains integers, you need to convert your short into an integer first, for example, by using CInt:

Dim myArray As Integer() = {5}
Dim value As Short = 5
Console.WriteLine(Array.IndexOf(myArray, CInt(value)))  ' Prints 0

Edit: Note that the declared type has nothing to do with this. Let's declare the array as Object, since that's what you mentioned in your comment (note that the following example requires Option Strict Off, which is bad):

Dim myArray As Object = New Integer() {5}
Dim value As Object = 5S  ' Short literal
Console.WriteLine(Array.IndexOf(myArray, value))  ' still returns -1
Console.WriteLine(Array.IndexOf(myArray, CInt(value)))  ' returns 0

Note: You can make that conversion implicit by declaring your function as Public Sub SomeFunction(ByVal test As Integer).