Problems passing object array

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.
 
J

Jon Skeet [C# MVP]

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!)
 
D

Dave Sexton

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!)
 
T

tcomer

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!
 

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