开发者

How will an object with a value type and reference type be stored in .NET?

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 开发者_JS百科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.


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.


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.


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.


It was just a tricky question. I think the question was asked to you to check your knowledge about classes in dotnet. Classes are reference type. So in simple words it will go to the heap section.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜