Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ldstr internally implement newobj?

Tags:

c#

.net

jit

cil

il

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?

like image 278
m.edmondson Avatar asked Apr 11 '12 17:04

m.edmondson


2 Answers

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.

like image 169
Brian Rasmussen Avatar answered Oct 17 '22 17:10

Brian Rasmussen


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.

like image 1
Tigran Avatar answered Oct 17 '22 16:10

Tigran