Resolved Beginner C# multi-dimensional array (or reference) error

GregJ7

New member
Joined
Nov 23, 2024
Messages
2
Programming Experience
10+
Can someone tell me what is wrong with this code? I don't see what the error message (for the last statement) is referring to. The only object reference in that statement looks like it is dereferenced with [0,0] to an instance of the object to me.

ERROR 'Object reference not set to an instance of an object.'

C#:
public GridAttrs[,]? MyGrid;
public class GridAttrs
{
    public enum E_Choices : byte { First, Second, Third };
    public E_Choices selection;
}

private void Window_Loaded(Object sender, RoutedEventArgs e)
{
    MyGrid = new GridAttrs[30, 30];
    MyGrid[0,0].selection = GridAttrs.E_Choices.Second;  // ERROR 'Object reference not set to an instance of an object.'
}

Thanks.
 
You have created an array, but have not created any GridAttrs items and put in it. Array slot [0,0] is null.
 
C# is not C++. C# is more like Java in this respect. Where as C++ would have created the array with the objects in them, C# and Java require you to put the objects into the array.
 
Or use some loops.
 
If GridAttrs is as simple type as that it qualifies as a struct, which is a value type. When you create the array it is initialized with the default "value" of the type. For classes that are reference types that is null reference (no object), but for structs it is the default struct value, for example value 0 if it was type int (Int32 struct). So if you change GridAttrs to struct your code will work without need to create class objects.

 
Back
Top Bottom