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
- C# String Clone Method Example
- C# String Compare Method Example
- C# String CompareTo Method Example
- C# String Concat Method Example
- C# String Contains Method Example
- C# String Copy Method Example
- C# String CopyTo Method Example
- C# String EndsWith Method Example
- C# String Equals Method Example
- C# String GetEnumerator Method Example
- C# String GetHashCode Method Example
- C# String IndexOf Method Example
- C# String Insert Method Example
- C# String Intern Method Example
- C# String IsNullOrEmpty Method Example
- C# String IsNullOrWhiteSpace Method Example
- C# String LastIndexOf Method Example
- C# String Clone Method Example
- C# String Compare Method Example
- C# String CompareTo Method Example
- C# String Concat Method Example
- C# String Contains Method Example
- C# String Copy Method Example
- C# String CopyTo Method Example
- C# String EndsWith Method Example
- C# String Equals Method Example
- C# String GetEnumerator Method Example
- C# String GetHashCode Method Example
- C# String IndexOf Method Example
- C# String Insert Method Example
- C# String Intern Method Example
- C# String IsNullOrEmpty Method Example
- C# String IsNullOrWhiteSpace Method Example
- C# String LastIndexOf Method Example
Comments
Post a Comment