afaolek
afaolek

Reputation: 8811

Should the stack be really allocated in a C# program?

From what I know of C# (I believe I am right), value types are allocated on the stack and reference types are alllocated on the heap. But if a field in a class is value type, it is allocated on the heap rather than on the stack (I'm still right, right?).

With that said, I also know that every C# program is a class and is made up of classes. That should imply that any variable declared in a C# program, value type or reference type, should be allocated on the heap.

What I can infer, then, is that the stack may not be really used in a C# program. I say 'may' because there could be extraordinary cases, not that I know one, though.

Upvotes: 1

Views: 72

Answers (2)

Christos
Christos

Reputation: 53958

A reference type is stored in the heap. This is true for the value types that are contained in the reference type. On the contrary in the stack is stored the reference to the object that is stored in the heap.

Regarding the variables that are local to a method that 500 - Internal Server Error has pointed out holds. They are allocated to the stack.

Upvotes: 1

You are mostly correct :)

Variables that are local to a method, however, are indeed allocated from the stack. This is the whole truth for value types. For reference types, the actual object, string, array, and so on, is allocated on the heap, but the pointer itself is allocated on stack.

Upvotes: 4

Related Questions