0

I'm new to C# and looking at arrays.

I'm wondering why the call to i.GetType() results in a NullReferenceException (Object reference not .....) ?

       int[][] myJagArray = new int[5][];
       foreach (int[] i in myJagArray) { Console.WriteLine(i.GetType()); }

Many thanks.

4

3 回答 3

4

In C#, value types (such as Int32) will be initialized to their zero'ed out values. For example:

int[] foo = new int[3];

Will create an array of 3 zeros. Printing:

Console.WriteLine(foo[1].GetType().Name);

Would give you Int32.

However, an Array type is a reference type. These are initialized to null by default.

For that reason, when you refer to the first item in int[5][], which is an array, you'll get a null as it hasn't yet been initialized. When you try to call GetType() on this, you'll see a NullReferenceException.

于 2013-02-07T17:42:44.517 回答
2

You are getting this error because your second dimension is null.

Try this:

int[][] myJagArray = new int[5][];
myJagArray[0] = new int[] { 1, 2, 3 };

foreach (int[] i in myJagArray) 
{
    if (i != null)
        Console.WriteLine(i.GetType());
    else
        Console.WriteLine("null");
}

Result of this will be:

System.Int32[]
null
null
null
null

You get first row not equal to null because we added this line:

myJagArray[0] = new int[] { 1, 2, 3 };
于 2013-02-07T17:37:17.543 回答
1

You have just declared you jagged array which gets default values as null

so you need to initialize those arrays as:

myJagArray[0] = new int[] { 1, 5, 7, 9 }; // put whatever values you want here
myJagArray[1] = new int[] { 0, 4, 6 };
myJagArray[2] = new int[] { 11, 22 };
........
myJagArray[4] = new int[] {12,23,45};
于 2013-02-07T17:48:32.140 回答