C# String Intern Method Example

In this source code example, we will demonstrate the usage of String.Intern() method in C# with an example.

The C# Intern() method is used to retrieve references to the specified String. It goes to the intern pool (memory area) to search for a string equal to the specified String. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to the specified String is added to the intern pool, then that reference is returned.

C# String Intern Method Example

using System;

public class StringDemo
{
    public static void Main(string[] args)
    {
         string s1 = "sourcecodeexamples";
        
         string s2 = string.Intern(s1);    
         
         Console.WriteLine(s1);  
         Console.WriteLine(s2);  
        
    }

}

Output:

sourcecodeexamples
sourcecodeexamples

C# String Intern Method Example - Check for Equals Example

The following example uses three strings that are equal in value to determine whether a newly created string and an interned string are equal.

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}");
    }
}

Output:

s1 == MyTest
s2 == MyTest
s3 == MyTest
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True

Related C# String Examples

References


Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course