Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is c# 6.0 nameof() result interned?

From what I can read the compiler just emits a string and nothing else really happens?

Is there any reason that the results of this call couldn't be interned? For a nameof(MyClass), if it happens a lot, it could, theoretically be worth it?

like image 383
tigerswithguitars Avatar asked Feb 09 '23 07:02

tigerswithguitars


1 Answers

Yes, it will be interned just as any other string literal.

This can be demonstrated with this TryRoslyn example where this:

public void M() 
{
    Console.WriteLine(nameof(M));
}

Is complied into this IL:

.method public hidebysig 
    instance void M () cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 11 (0xb)
    .maxstack 8

    IL_0000: ldstr "M"
    IL_0005: call void [mscorlib]System.Console::WriteLine(string)
    IL_000a: ret
} // end of method C::M

You can see that "M" is being loaded using ldstr which means it is interned:

"The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning")."

From OpCodes.Ldstr Field

This can also be verified by running this example, which prints true:

Console.WriteLine(ReferenceEquals(nameof(Main), nameof(Main)));
like image 169
i3arnon Avatar answered Feb 12 '23 09:02

i3arnon