Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

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

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

string mystring = "Hello World"

Is variable mystring in the same context as the object I declare it? And the data "Hello World" on the heap?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...