OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJECT. but the code is correct

S

sravan_reddy001

here Box is an user defined class
Box[] b;
b = new Box[100];
//b = new Box[10, 10];
/*b = new Box[10][];
for (int i = 0; i < 10; i++)
{
b = new Box[10];
}*/
if(size==0)
size = 4;// defaullt size
for (int i = 0; i <size; i++)
{
for (int j = 0; j < size; j++)
{
if (i == 0)
b[i * size + j].N = false;// "OBJECT REFERENCE
NOT SET TO AN INSTANCE OF AN OBJECT."
if (i == size - 1)
b[i * size + j].S = false;
if (j == 0)
b[i * size + j].W = false;
if (j == size - 1)
b[i * size + j].E = false;
}
}

why is that error coming..
i had declared the variable and also allocated memory using the new
keyword..

It is saying to "USE new KEYWORD TO CREATE AN OBJECT INSTANCE"
 
P

Peter Duniho

sravan_reddy001 said:
[...]
why is that error coming..
i had declared the variable and also allocated memory using the new
keyword..

Yes, but you never initialized the allocated memory to anything useful.

This sort of search is useful for these kinds of questions:
http://groups.google.com/group/micr...arp/search?q="OBJECT+REFERENCE+NOT+SET"+array

Here's a result from the above search that is pretty much identical to
the problem you're having:
http://groups.google.com/group/micr...read/thread/9de1ac7c06c890eb/167d26b8ad1ccc40

Pete
 
M

Marc Gravell

i had declared the variable and also allocated memory using the new
keyword..
No; the code never creates any Box instances; it is commented out (and
uses jagged-array syntax); arrays of reference-types (classes)
initialise all values to null; you need something like:

for (int i = 0; i < 100; i++) {
b = new Box();
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top