views:

64

answers:

3

This is likely a scoping issue but the following code dies. I build a multi-dimensional array from 2 classes, Cell and Map. The map is an X by Y sized grid of Cells. Pretty normal so far (I keep re-writing this same program when I learn a new language). For brevity I'll just post the classes and a basic test that reflects the error. When I go to print the map the whole grid array I initalized during the construtor vanishes when I go to print (Null exception since grid ends up empty some how...)

//misc using up here

namespace Mapper {
class Program {

static void Main(string[] args)
{ //TODO Parser

 int max_x=2;
 int max_y=2;

 Map myMap = new Map(max_x,max_y);
 myMap.print();


}

class Cell
{
 public char type='o';
 public Cell(char inittype){
 this.type=inittype;
 }

 public void printCell(){
 Console.Write(this.type); }

 public void set(char value){
 this.type = value; }
}

class Map
{
 private int max_X; //global
 private int max_Y; //global
 public Cell[,] grid; //global

 public Map(int maxX, int maxY) {
 Cell[,] grid = new Cell[maxX, MaxY];
 this.max_X = maxX; //Store constructor provided dimensions for global use
 this.max_Y = maxY; 
 for(int yv=0; yv &lt max_Y; yv++){
  for(int xv=0, xv &lt max_X;xv++){
    grid[xv,yx] = new Cell('x');
  }
 }

 public void print() {
 for(int yv=0; yv &lt max_Y; yv++){
  for(int xv=0, xv &lt max_X;xv++){
    grid[xv,yx].printCell();
  }
 }

}}

Running a trace everything looks fine until the Map myMap line completes... in other words it seems like the constructor doesn't "stick" and I get an empty grid in the end (they all go null.) I can only assume it's a scope issue in some way... what am I missing....? Did I bork the constructor?

+8  A: 

The problem is here:

public Cell[,] grid; //global

public Map(int maxX, int maxY) {
    Cell[,] grid = new Cell[maxX, MaxY];
    ...

You've declared an instance member called grid and a local variable called grid, but you're only updating the local variable.

To fix it, change the last line mentioned above to this:

grid = new Cell[maxX, maxY];

You also have a large number of compile errors in your code - the code in the question could not possibly be the code you are running. Next time please use copy and paste to copy the code into the question.

Also the comment //global is misleading. An instance member is not a global variable. The closest equivalent to a global variable in C# is a static member.

Mark Byers
The global reference was "global visibility within the class itself" rather then the whole program.
Idgarad
A: 

In your constructor, you're assigning to a local grid variable, not the class grid variable.

Cell[,] grid = new Cell[maxX, MaxY];

should be

this.grid = new Cell[maxX, maxY];
Sam T.
That worked like a champ! Thank you.
Idgarad
A: 

In the constructor, you're declaring Cell[,] grid, which is hiding the class-level Cell[,] grid. :)

James B
*@#$, you people are too fast : D
James B