0
votes

I have a simple console application in .net 4.5.

public class Program
{
    public static void Main()
    {
        string s1 = "s1";
        string s2 = "s1";

        Console.WriteLine(ReferenceEquals(s1, s2));
    }
}

This gives true because of string interning. However, when I add the CompilationRelaxations attribute to the AssemblyInfo file, I'm still seeing true as the output.

[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]

Even adding the attribute to my Program class does not seem to change the output. [CompilationRelaxations(CompilationRelaxations.NoStringInterning)]

Changing it to a .net 4.0 application does not have any effect either.

What am I missing?

1
This is a pure guess, but chances are that the compiler optimizes the two string constants for you, before the interning gets a chance to do its thing at runtime. Try adding a separate class, in a separate file, and make a function public static string s1() {return "s1";} to it. Then call that function fro your main, and compare the result to an "s1" constant defined inside "main". My guess is that this would compare equal only with the interning turned on.Sergey Kalinichenko
@dasblinkenlight: I don't think so. Adding [MethodImpl(MethodImplOptions.NoOptimization)] doesn't help.Cheng Chen

1 Answers

1
votes

Here is a quote from the documentation:

Marks an assembly as not requiring string-literal interning.

It doesn't prevent the compiler from doing string interning, just providing a hint that it's not required. The documentation for it is quite poor, both in MSDN and the CLI spec. See also this MSDN forum post.