.NET stack and heap, what goes where when I declare a string?

后端 未结 3 1526
北荒
北荒 2020-12-10 16:58

If I execute this line I create a string which is a reference.

string mystring = \"Hello World\"

Is variable mystring in the

相关标签:
3条回答
  • 2020-12-10 17:05

    Read these... From Eric Lippert... he wrote the C# compiler! Should answer all your questions.

    http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx

    http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

    0 讨论(0)
  • 2020-12-10 17:11

    Official Answer: it's an implementation detail and you don't need to know.

    It is of course knowable for a specific (current) version of the framework:

    1) if this is inside a method, then mystring is a reference variable, usually on the stack. But when it is captured, or when the method is async, or ... it is moved to the heap.

    2) if this is inside a class, then each instance will contain a mystring reference as a field, stored on the heap.

    In both cases there is an anonymous string object on the heap containing "Hello World"

    0 讨论(0)
  • 2020-12-10 17:20

    It's complicated. First of all the strings are interned by the compiler, so your string could be a reference to a previously allocated string object. Second of all it is an implementation detail, which you shouldn't worry about, and which can change at any of the next C#/.NET versions. I'll refer you to the excellent post by Eric Lippert, who is one of the people who write the C# compiler: here

    0 讨论(0)
提交回复
热议问题