C# casting, Indexof

87 Views Asked by At

I'm new to programming (for 5 days). I wrote this code but index is always -1 (when 2 is expected) and I couldn't fix it.

My teacher wrote me just that:

Casting, Array.IndexOf(geburtsjahr, (int)1966);

I tried but still same.

This is my relevant code:

var geburtsjahr = new short[4] { 1998, 1992, 1966, 2006 }; 

// Expected: 2, Actual: -1
int index = Array.IndexOf(geburtsjahr, (int)1966);

Console.WriteLine(index); 

I tried to see right index number (should be 2).

2

There are 2 best solutions below

0
Enigmativity On

It works if you do either of these:

(1)

var geburtsjahr = new short[4] { 1998, 1992, 1966, 2006 };
int index = Array.IndexOf(geburtsjahr, (short)1966);

(2)

var geburtsjahr = new int[4] { 1998, 1992, 1966, 2006 };
int index = Array.IndexOf(geburtsjahr, (int)1966); //or just 1966 without the cast.

The issue is that there is no int of any value in an array of short values, no matter what the numbers represent to us humans.

0
Dmitry Bychenko On

The main problem with your code is that you have short[] array and int value to find in it and .net can't do implicit cast from int to short for you. There are several overload Array.IndexOf implementations:

In case of Array.IndexOf(Array, Object) .net looks for an object (boxed int value) in an array of objects. The array contains short values (which can be boxed, but still short), not int, so .net can't find int.

Possible corrections:

  1. Make geburtsjahr have int values:
var geburtsjahr = new int[4] { 1998, 1992, 1966, 2006 }; 
  1. Search for short:
int index = Array.IndexOf(geburtsjahr, (short)1966);
  1. Let .net do the cast for you (1966 will be of type short):
int index = Array.IndexOf<short>(geburtsjahr, 1966);