0

hi every one i have few question

1)

class ClassName 
{
    public int[] a = new int[100];
}

what happens when object of this class is created i mean where is the array of integers stored at, on the Stack [value type] or on the Heap [Reference Type]

i am confused as per the specs value types are stored on Stack then the array will be stored on stack .

but the Reference types are created on Heap as per the specs

please guys help me understand this . i dont want to write code without knowing what is happening behind the scenes

thanks in Advance

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
Constantine
  • 99
  • 1
  • 10
  • possible duplicate of [Fields of class, are they stored in the stack or heap?](http://stackoverflow.com/questions/2565331/fields-of-class-are-they-stored-in-the-stack-or-heap) – Markus Jan 26 '14 at 20:22
  • Values types are not allocated on the stack, they are allocated inline. Arrays are reference type, so the array data is stored on the heap, while a reference to it is stored in the instance of `ClassName`. – Lee Jan 26 '14 at 20:23
  • Duplicate question, but here's a really good answer: http://stackoverflow.com/a/2561622/67038 – JMarsch Jan 26 '14 at 20:31
  • @Lee where will be "public int a =12;" stored at ? – Constantine Jan 26 '14 at 20:39
  • It depends. Could be stack or heap. What is the context? – David Heffernan Jan 26 '14 at 20:47
  • 1
    @Constantine - It will be stored as part of the containing struct/object data. – Lee Jan 26 '14 at 20:48
  • Value types are *eligible* to be stored on the stack. There is no requirement that they must be stored there. Some good additional reading: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx – Mike Zboray Jan 26 '14 at 20:54

1 Answers1

4

There are no value types here. So the question is moot. Both ClassName and int[] are reference types.

If a value type is declared as an automatic local it is stored on the stack. If it is declared inside another type, it is stored inside that other type.

It is one of the great un-dying myths of C# that value types are always stored on the stack.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490