c# - "Object reference not set to an instance of an object" when initialising multi-dimensional array -
I am running the following code on an asp.net razor page (cshtml) and scared "object reference is not set" For the example of an object "problem" can anyone help me with this problem? The code I am using is below and the problem line is the
menu [1] [0] = "about"; string [] [] menu = new string [5] []; Menu [0] = new string [2]; // First menu item menu [0] [0] = "Home"; // First menu URL menu [0] [1] = "#"; // second menu item menu [1] [0] = "about"; // second menu URL menu [1] [1] = "#"; // third menu item menu [2] [0] = "contact"; // Third menu URL menu [2] [1] = "#"; // Fourth menu item menu [3] [0] = "more info"; // Fourth menu URL menu [3] [1] = "#"; // fifth menu item menu [4] [0] = "test"; // Fifth menu URL menu [4] [1] = "#"; Thank you in advance
You only initiated the first element Try to loop in Menu :
for (int i = 0; i Alternatively, you can write it like this:
string [] [] menu = {new string [] {"home" New string [] {"About", "#"}, New string [] {"Contact", "#"}, New string [] {"More info", "#"}, New string [] {"test", "#"}}; Or use a rectangular array instead:
string [,] menu = {{"home", "#"}, {" About "" # "}, {" contact "," # "}, {" more info "," # "}, {" test "," # "}}; And since your second element is continuous, you do not need to store it - in this case you can use a string [] .
string [] menu = {"home", "about", "contact", "more info", "test"};