-2
public Grid (int width, int height, char defaultCharacter) {
    for (int n = 0; n <= height; n++) {
        List<char> aRow;
        for (int i = 0; i <= width; i++) {
            aRow.Add(defaultCharacter);
        }
        this.grid.Add(aRow);
    }
}

This is some of my code. When I run this on Xamarin Studio it gives me an error on these lines saying "Use of unassigned local variable 'aRow'":

  • aRow.Add(defaultCharacter);
  • this.grid.Add(aRow);

This function is in a class called Grid, with one variable:

List<List<char>> grid = new List<List<char>>();

Any ideas on why this variable is unassigned?

ZacG
  • 97
  • 9
  • 3
    Because you aren't assigning anything to it? What do you think the value of `aRow` is? – Lee Sep 27 '15 at 12:20
  • Good point :P Can you post that as an answer so I can accept it? – ZacG Sep 27 '15 at 12:21
  • 1
    you really didnt have to ask this question. your debugger does not show a red line? – M.kazem Akhgary Sep 27 '15 at 12:23
  • **possible duplicate** of [Use of unassigned local variable (Object)](http://stackoverflow.com/questions/12193700/use-of-unassigned-local-variable-object?rq=1) –  Sep 27 '15 at 12:25

1 Answers1

0

The variable that you didn't initialize is aRow. I think an average person knows that it doesn't have a value. So in order to solve this, you should give a value to it.

As you should already know, we use the = operator to give values to variables. So you can instantiate a new instance of List<char> like this:

aRow = new List<char> ();

And you may want to ask why it must have a value before you use it. Because sometimes a variable is null (nothing). Let's imagine what will happen if the value of aRow is null. aRow.Add will cause a NullReferenceException because it is nothing.

If you don't give the variable a value, the compiler doesn't know whether it is null or something else. Thus, it complains.

Sweeper
  • 213,210
  • 22
  • 193
  • 313