Skip to content

string.Intern works inconsistently with NativeAOT #12447

@kekekeks

Description

@kekekeks

Description

ReferenceEquals("ab", string.Intern(new StringBuilder().Append('a').Append('b').ToString())) returns true on coreclr and false with NativeAOT. The official documentation page https://learn.microsoft.com/en-us/dotnet/api/system.string.intern?view=net-9.0 states that it would return true.

Reproduction Steps

  1. copy-paste example from documentation:
// Sample for String.Intern(String)
using System;
using System.Text;

class Sample
{
    public static void Main()
    {
        string s1 = "MyTest";
        string s2 = new StringBuilder().Append("My").Append("Test").ToString();
        string s3 = String.Intern(s2);
        Console.WriteLine($"s1 == {s1}");
        Console.WriteLine($"s2 == {s2}");
        Console.WriteLine($"s3 == {s3}");
        Console.WriteLine($"Is s2 the same reference as s1?: {(Object)s2 == (Object)s1}");
        Console.WriteLine($"Is s3 the same reference as s1?: {(Object)s3 == (Object)s1}");
    }
}
/*
This example produces the following results:
s1 == MyTest
s2 == MyTest
s3 == MyTest
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/
  1. Run with NativeAOT, observe the following output:
s1 == MyTest
s2 == MyTest
s3 == MyTest
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: False

Expected behavior

NativeAOT is consistent with CoreCLR

Actual behavior

Liternal strings are not actually interned

Regression?

I guess? It worked since .NET Framework days.

Known Workarounds

No response

Configuration

.NET 10

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions