Initializing An Array inline

arct-075 This is part two of the discussion I started yesterday about the StackOverflowException, where I explained how memory gets allocated for the different types of variables we have in our systems and how understanding that can prevent the StackOverflowException.  The question came back with some code this time which looked something like this:

private mystruct[] m_struct = 
    new mystruct[6000000];
private mystruct[] GetStructArray()
{
    m_struct[0] = 
        new mystruct(3, 2);
    ...
    m_struct[5900000] = 
        new mystruct(5,4);
}
struct mystruct
{
    public mystruct(int i,int j)
    {
        m_i = i;
        m_j = j;
    }
    public int m_i;
    public int m_j;
}

Ugh!

So what we are actually doing here is

  • Creating an array of a structure
  • Initializing the array with new structure items inside a method.
  • Running out of stack space.

So the obvious question is, “How do we initialize the structure on the heap instead of the stack?”

Well, we sure can’t do it in a method.  Although breaking this up into several functions might help, it isn’t the best way to go about this.

Instead of even calling the method, we can initialize all of the elements when we create the array of structures using this syntax.

private mystruct[] m_struct = 
{ new mystruct(0, 4), 
    new mystruct(2, 3),
    new mystruct(5,7), etc...};

This creates the array and initializes all in one line.  And it does it all on the heap that is created when the class is instantiated.

This syntax also works for arrays of integers, strings, or any other type you might need to create an array of.

Related Post

  • StackOverflowException – What causes this?StackOverflowException – What causes this?
    Oner Yilmaz Asks: I am using C# Êxpress developer tool. I Intend to form 3D Mesh object by an array of 60.000 items. When I reach to appr. 19.000 items, I get the error message "An unhand...
  • iTextSharp – HTML to PDF – Writing the PDFiTextSharp – HTML to PDF – Writing the PDF
    Last week we parsed the HTML and created code that keeps track of the various attributes we are going to need when we create the PDF.  Today we will finish the code and create the Elements t...
  • Don’t be such a #@%#! Lazy Programmer!Don’t be such a #@%#! Lazy Programmer!
    I get several questions a week via the “Click Here to Ask a Question.”  I would like to say I answer all of them, but I don’t. The number one reason I don’t answer a question is because I’...
  • Response.Redirect() and JavaScriptResponse.Redirect() and JavaScript
    Yesterday we covered issues surrounding using Response.Redirect in server side code. We noted that not handing it correctly could prevent code from running on the server that we want to run. T...
  • CSharp EnumCSharp Enum
    It is often tempting when working with your code to test against static values in your system.  For example: if (i == 1) { // do something } else if (i == 2) { // do something } O...