String is not value type, but we still use it like it's value type. So, is string s;
compiled to something like string s = new String(..);
?
Asked
Active
Viewed 143 times
0

theateist
- 13,879
- 17
- 69
- 109
-
When you do `string s;`, nothing is instantiated. – Bertrand Marron Mar 11 '12 at 10:14
-
But, if it's not a value type it has to be instantiated with `new`, isn't it? – theateist Mar 11 '12 at 10:15
-
@theateist what would you expect this to do: `string s = null`? – Davin Tryon Mar 11 '12 at 10:22
-
2string s; or object o; are the same thing. Each are stack space initialized with null (supposing they are local variable). Then when you decide to use it, you will be forced to inizialize with a real value like s = string.Empty; or s = "Hello world"; – Steve Mar 11 '12 at 10:23
-
1A string variable is instantiated when you assign some text to it. http://msdn.microsoft.com/en-us/library/system.string.aspx – Silvermind Mar 11 '12 at 10:25
2 Answers
2
When you define string s;
you only define a reference, which currently points to nothing at all. As string is a reference type, the compiler will not generate string s = new String(..);
. You may understand it as string s = null;
will be the compilation result.
For value types, such as int, the case is different. For example, when you define int i;
, it will compile to int i = 0;
where 0 is the default value.

Lex Li
- 60,503
- 9
- 116
- 147
0
I figured out my confusion: after reading this post I understood that stack will hold reference to s
that will allocated in heap after initialization.
-
I don't know who down voted, but your understanding here is much better than the one you expressed in the question. However, it still only covers some of the string mystery. There is another important thing that makes string special, http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx – Lex Li Mar 11 '12 at 11:05