Does ldstr internally implement newobj?

▼魔方 西西 提交于 2019-12-10 13:28:59

问题


As we all know strings are implicitly instantiated, meaning that we don't have to use new in order to get a reference to an object of one.

Because of this it was always my belief that the framework is taking care of this, and hence I would get identical IL if I did something like this:

String first = new String(new char[] {'a'});
string second = "a";

However it appears that the first line is done using newobj instance void [mscorlib]System.String::.ctor(char[]) and the second ldstr "a".

So in order to obtain a string reference, does ldstr internally call newobj and where can I see the specification / details to back this up?


回答1:


ldstr gives you the reference to the literal string as per the documentation (remember literal strings are interned per default, so they are only created once). The first statement creates a regular instance of string using the newobj instruction as expected.




回答2:


string simply follows tha basic guideline for reference object types, that's why on new you see newobj.

Infact if you try to write something like this, it will not generate newobj:

int a = new int();
a = 2;  
Console.WriteLine(a);

The resulting IL will be

IL_0000:  ldc.i4.0    
IL_0001:  stloc.0     
IL_0002:  ldc.i4.2    
IL_0003:  stloc.0     
IL_0004:  ldloc.0     
IL_0005:  call        System.Console.WriteLine

if you write just

int a = 2;  
Console.WriteLine(a);

result IL will be

IL_0000:  ldc.i4.2    
IL_0001:  stloc.0     
IL_0002:  ldloc.0     
IL_0003:  call        System.Console.WriteLine

No difference from allocation point of view (there is missed line naturally), cause we are talking about value type.



来源:https://stackoverflow.com/questions/10111194/does-ldstr-internally-implement-newobj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!