Array Initialization

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?bXIgcGVhbnV0?=

    #1

    Array Initialization

    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.Initiali ze(); but that didn't work.



  • Jon Skeet [C# MVP]

    #2
    Re: Array Initialization

    mr peanut <mrpeanut@discu ssions.microsof t.comwrote:

    <snip>
    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.Initiali ze(); 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.

    --
    Jon Skeet - <skeet@pobox.co m>
    http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
    If replying to the group, please do not mail me too

    Comment

    • not_a_commie

      #3
      Re: Array Initialization

      ComplexNumber should absolutely be a struct.

      Comment

      Working...