2

Someone has chosen to mark this as duplicate, and though I can appreciate trying to clean up a question asking community, the I have examined the "duplicated" material in detail prior to posting my question. As indicated in my question below, I show the outputs of the issue in question, which has no nulls.

I have a method I create based on a user selecting a spinner value that looks like this:

    public void terrain_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Spinner spinner = (Spinner)sender;
        var ttype = string.Format("{0}", spinner.GetItemAtPosition(e.Position));
        Console.WriteLine(ttype);
        foreach (var item in Terrainstr) { Console.WriteLine(item); }
        var index = Array.FindIndex(Terrainstr, x => x.Contains(ttype));

As you can see, the string ttype is simply the selection the user makes with the spinner.

I have a string array Terrainstr that's initialized before OnCreate like this:

string[] Terrainstr = new string[10];

I populate it later with string fragments based on a number of user selections.

You'll notice I have Console.WriteLine commands in the method. My (annotated) output when that method is used is:

Fast (ttype)
Stock (Terrainstr[0])
Slow 
Slow Sand 
Slow Sand Rocks Whoops 
Slow Sand Mud Rocks Whoops 
Slow Mud Rocks Whoops 
Slow Mud Rocks (Terrainstr[6])

I want to find which indeces of Terrainstr contain ttype. In this case, it wouldn't fit it at all. I get a null exception using the command shown here:

var index = Array.FindIndex(Terrainstr, x => x.Contains(ttype));

Please advise!

1 Answers1

4

Basically your array is of size 10 and you only have 8 elements in it (based on Console.WriteLine output) so the last two are nulls.

Array.FindIndex doesn't check if the element is null or not and pass it to your lambda where you try to run .Contains. If it's null then you get a NullReferenceExeception.

Filter you array and only do the FindIndex on non-null elements.

var index = Array.FindIndex(Terrainstr, x => x != null && x.Contains(ttype));
Paweł Łukasik
  • 3,893
  • 1
  • 24
  • 36