Array Initialization

G

Guest

I have a class:
public class ComplexNumber
{
public ComplexNumber()
{
this.Real = 0;
this.Imaginary= 0;
}
double Real;
double Imaginary;
(other stuff)
}

I have another class:
public class Test
{
Private void MyMethod
{
Blah, Blah, ...
ComplexNumber[,] result = new ComplexNumber[m + 1, n + 1];
string str = result[100, 50].ToString(); //Here
(Other stuff)
}
}

Inspecting result at the line with the "Here" comment I see that all of the
array elements are null. I can loop constructors for every array element but
I am wondering why the class default constructor does not do this for me when
I make the aray. Is there a better way to initialize the "result" array. I
tried result.Initialize(); but that didn't work.
 
J

Jon Skeet [C# MVP]

Inspecting result at the line with the "Here" comment I see that all of the
array elements are null. I can loop constructors for every array element but
I am wondering why the class default constructor does not do this for me when
I make the aray.

Why would it? Put it this way: by *not* doing it automatically, there
can't be any wasted operations. If it automatically called the
parameterless constructor, then:

1) What would happen if there *wasn't* a parameterless constructor?
2) You'd be very wasteful if you wanted to create the array and then
fill it with specific values.
Is there a better way to initialize the "result" array. I
tried result.Initialize(); but that didn't work.

Nope, just initialize each value as you want it. Alternatively, make
ComplexNumber a struct, which is more appropriate anyway, IMO.
 

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