views:

127

answers:

3

In .NET, integer data type is a value type(stack) and String is a reference type(heap).

So If a class A has an integer, and a string type object in it, and a class B creates an object of class A, then how will this object of class A be stored in memory? In stack, or in a heap?

This was asked in my Microsoft interview. Need to understand how I fared.

+2  A: 

In general, only value types that are local variables end up on the stack. The rest, including fields of classes, is stored on the heap.

In fact, the situation is more complex; see the link to Eric Lippert's Blog provided in Rex M's answer.

Heinzi
+9  A: 

Eric Lippert just wrote about this:

It is simply false that the choice of whether to use the stack or the heap has anything fundamentally to do with the type of the thing being stored.

The true story is:

"in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value."

Most importantly, he stresses that you simply should not care where a type lives. You should care where things of a certain lifetime live.

Rex M
A: 

If I recall correctly, Objects are always reference types, regardless of their member types.

So, any object of Class A will be stored on the heap.

Daniel Mallott