Jagged array problem

A

azz131

Hi, i am haveing problems with this code

namespace test
{
class Program
{
class MyClass{
public int x;
int y;
}
static void Main(string[] args)
{
MyClass[][] myclass=new MyClass[4][];
myclass[0]=new MyClass[5];

myclass[0][0].x=10; // error here
}
}
}
I am getting this error

Exception System.NullReferenceException was thrown in debuggee:
Object reference not set to an instance of an object.

What am i doing wrong?
 
A

Alberto Poblacion

azz131 said:
Hi, i am haveing problems with this code
[...]
What am i doing wrong?

You have not created any instance of MyClass, only of an array of
MyClass. Here is the fixed code:

namespace test
{
class Program
{
class MyClass{
public int x;
int y;
}
static void Main(string[] args)
{
MyClass[][] myclass=new MyClass[4][];
myclass[0]=new MyClass[5];
myclass[0][0]=new MyClass(); //<--You missed this
myclass[0][0].x=10; // error here
}
}
}
 
L

Ludwig

Hi, i am haveing problems with this code

namespace test
{
class Program
{
class MyClass{
public int x;
int y;
}
static void Main(string[] args)
{
MyClass[][] myclass=new MyClass[4][];
myclass[0]=new MyClass[5];

myclass[0][0].x=10; // error here
}
}
}
I am getting this error

Exception System.NullReferenceException was thrown in debuggee:
Object reference not set to an instance of an object.

What am i doing wrong?


MyClass[][] myclass=new MyClass[4][];
myclass[0]=new MyClass[5];
myclass[0][0] = new MyClass(); <----
myclass[0][0].x=10; // no error here
 
M

Marcin Hoppe

Hi, i am haveing problems with this code

namespace test
{
class Program
{
class MyClass{
public int x;
int y;
}
static void Main(string[] args)
{
MyClass[][] myclass=new MyClass[4][];
myclass[0]=new MyClass[5];

myclass[0][0].x=10; // error here
}
}}

I am getting this error

Exception System.NullReferenceException was thrown in debuggee:
Object reference not set to an instance of an object.

What am i doing wrong?

When you create an array, its elements are initialized to the default
value of the type of elements. For reference types, such as your
class, it is null. It would be zero for any numeric type.

What you must do is to create objects to store in your array:

myclass[0][0] = new MyClass();
myclass[0][0].x = 5;
 

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