Is the C # 6.0 nameof () result interned?

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

Is there a reason why the results of this call cannot be interned? With a nameof(MyClass) , if this happens a lot, can it theoretically be worth it?

+4
source share
2 answers

Yes, it will be interned like any other string literal.

This can be demonstrated with this TryRoslyn example , where it is:

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

Runs in 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" loads with ldstr , which means it is interned:

"The common language infrastructure (CLI) ensures that the result of two ldstr commands related to two metadata tokens that have the same sequence of characters returns exactly the same string object (a process known as" string interning ").

From Field OpCodes.Ldstr

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

 Console.WriteLine(ReferenceEquals(nameof(Main), nameof(Main))); 
+6
source

If the compiled output is a string literal, it will be interned. String literals are interned in the .NET environment.

+2
source

All Articles