-2

I want to find a way to convert object[] elements dynamically and find string "needle" my problem come from first array case

  var haystack_1 = new object[]{'3', "123124234", null, "needle", "world", "hay", 2, '3', true, false};
  var haystack_2 = new object[]{"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};
  var haystack_3 = new object[]{1,2,3,4,5,6,7,8,8,7,5,4,3,4,5,6,67,5,5,3,3,4,2,34,234,23,4,234,324,324,"needle",1,2,3,4,5,5,6,5,4,32,3,45,54};

   var index =  Array.FindIndex(haystack_1,item => item.ToString().Equals("needle"));
    Console.WriteLine(index);

error

Run-time exception (line 13): Object reference not set to an instance of an object.

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.] at Program.b__0(Object item) :line 13 at System.Array.FindIndex[T](T[] array, Int32 startIndex, Int32 count, Predicate1 match) at System.Array.FindIndex[T](T[] array, Predicate1 match) at Program.Main() :line 13

NinjaDeveloper
  • 1,303
  • 3
  • 14
  • 41

2 Answers2

1

Your problem is because you are trying to get ToString from a null object.

In haystack_1 you have a null object:

...

var index =  Array.FindIndex(haystack_1, item => item != null && item.ToString().Equals("hay"));

Fiddle: http://rextester.com/JZM30549

This will solve the problem, with this code you will check the object (with item != null) before you try to convert anything to a string.

z3nth10n
  • 1,905
  • 2
  • 16
  • 40
1

That error occurred because you are trying to get ToString from a null object.

You can use Convert.ToString method which will handle null object for you.

The main difference is that ToString() can't handle null while Convert.ToString() can handle null value.

var index = Array.FindIndex(haystack_1, item => Convert.ToString(item).Equals("needle"));
Gaurang Dave
  • 3,650
  • 2
  • 12
  • 30