Search code examples
c#.netlarge-object-heap

C# Huge object initializer throws Stack Overflow error


I need to build an object which consists of almost 20000 nested objects (in multiple levels). Each object is a simple database entity with 1-5 fields or a list of entities. I am using inline object initializer to initiate my root object.

new OUTPUT() { XREF_CATALOG_MATERIALS = xrefCatalogMaterials.Find(x => x.MATERIAL.PART_NUM.Equals("xxxx")), FUNCTION = new FUNCTION() {...

I tried running on both x86 and x64 mode and in both cases I get stackoverflow exception. The same code and logic works fine on the other cases that my object is not that big (around 6000 nested objects)

Is there any way to increase .Net applicationheap size? any suggestion that I can use to solve that issue?


Solution

  • from that description you don't have a problem with heap size. you have a problem with stack size. looks like you're trying to invoke too many nested functions. every function call has an effect on stack. Stack is much smaller than heap and it is relatively easy to overflow it. Easiest way is a recursion.

    https://msdn.microsoft.com/en-us/library/system.stackoverflowexception(v=vs.110).aspx

    StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion.