0

It's not the first time I'm getting this error on snippets I found on forums and I cannot understand why. Also I'm yet a C# noob.

Whenever I try something like arr.Max(x => x.Length) I'm getting a NPE on x in x.Length. Something must be wrong with the param variable I'm passing, because I only get this error on execution.

private string[,] jaggedTo2D(string[][] arr)
{
    string[,] arr2 = new string[arr.Length, arr.Max(x => x.Length)];
    for (var i = 0; i < arr.Length; i++)
    {
        for (var j = 0; j < arr[i].Length; j++)
        {
            arr2[i, j] = arr[i][j];
        }
    }

    return arr2;
}
spirit
  • 3,265
  • 2
  • 14
  • 29
  • Is any of `arr` elements null? – shahkalpesh Jul 24 '16 at 21:15
  • 1
    The snippets usually does not include error checking. Apparently the variable `arr` is not `null`, but some element is (jagged array is array of arrays). – Ivan Stoev Jul 24 '16 at 21:16
  • This question should not be considerated a duplicate of http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it. While it is about a null reference exception this one is specifically about a null reference exception inside a Linq function, which has some considerations of it's own. – André Sampaio Jul 24 '16 at 21:25
  • The real answer to your question is that you're passing in an array of arrays (a jagged array), where at least one of the members (in the first rank of the array) hasn't been initialised with a new array inside it. – Lunster Jul 24 '16 at 21:31

1 Answers1

1

try the following:

    private string[,] jaggedTo2D(string[][] arr) {
        string[,] arr2 = new string[arr.Length, arr.Max(x => null != x ? x.Length : 0)];
        for (var i = 0; i < arr.Length; i++) {
            for (var j = 0; j < arr[i].Length; j++) {
                arr2[i, j] = arr[i][j];
            }
        }

        return arr2;
    }

I've added check for the null element.

spirit
  • 3,265
  • 2
  • 14
  • 29