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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With