Problems passing object array

  • Thread starter Thread starter tcomer
  • Start date Start date
T

tcomer

This is what I'm trying to do:

class MyClass
{
private MyObject [] object;

public MyClass()
{
object = new MyObject[10];
MyFunction(ref object);
....

protected MyFunction(ref MyObject [] object)
{
object[0].myVar= "value";
....

this is giving me a NullReferenceException on the statement in
MyFunction. The constructor of the object initializes all variables to
a default value.
 
tcomer said:
This is what I'm trying to do:

class MyClass
{
private MyObject [] object;

public MyClass()
{
object = new MyObject[10];
MyFunction(ref object);
...

protected MyFunction(ref MyObject [] object)
{
object[0].myVar= "value";
...

this is giving me a NullReferenceException on the statement in
MyFunction. The constructor of the object initializes all variables to
a default value.

Creating an array of a class type doesn't create any instances of that
type - it creates an "empty" array with as many "slots" as you've asked
for, with the value in each "slot" being null to start with. It sounds
like you want to do:

for (int i=0; i < object.Length; i++)
{
object = new MyObject();
}

before your method call.

(By the way, I assume you're not *really* using "object" as a variable
name... I really hope not!)
 
Hi Jon,
(By the way, I assume you're not *really* using "object" as a variable
name... I really hope not!)

It wouldn't even compile unless it's escaped with the literal token "@"
anyway:

protected MyFunction(ref MyObject[] @Object) { ... }

But I agree, that's ridiculous :)

--
Dave Sexton

Jon Skeet said:
tcomer said:
This is what I'm trying to do:

class MyClass
{
private MyObject [] object;

public MyClass()
{
object = new MyObject[10];
MyFunction(ref object);
...

protected MyFunction(ref MyObject [] object)
{
object[0].myVar= "value";
...

this is giving me a NullReferenceException on the statement in
MyFunction. The constructor of the object initializes all variables to
a default value.

Creating an array of a class type doesn't create any instances of that
type - it creates an "empty" array with as many "slots" as you've asked
for, with the value in each "slot" being null to start with. It sounds
like you want to do:

for (int i=0; i < object.Length; i++)
{
object = new MyObject();
}

before your method call.

(By the way, I assume you're not *really* using "object" as a variable
name... I really hope not!)
 
No, that was just the name that I used in the example.. I know better
;)

That solved my problem, thanks a lot! I've moved from C++ to C# and I'm
still trying to get used to the differences between the two. Much
appreciated!
 
Back
Top