Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to retrieve the system's reference to the specified String in C#?
The string.Intern() method in C# retrieves the system's reference to the specified string from the intern pool. The intern pool is a table maintained by the .NET runtime that contains references to all string literals and interned strings to optimize memory usage by ensuring that identical strings share the same memory location.
Syntax
Following is the syntax for the string.Intern() method −
public static string Intern(string str)
Parameters
-
str − The string to search for in the intern pool.
Return Value
Returns a reference to the string in the intern pool if it exists, or adds the string to the intern pool and returns the reference if it doesn't exist.
Using string.Intern() Method
Example
using System;
public class Demo {
public static void Main(string[] args) {
string str1 = "David";
string str2 = string.Intern(str1);
Console.WriteLine("String1 = " + str1);
Console.WriteLine("System reference of String1 = " + str2);
}
}
The output of the above code is −
String1 = David System reference of String1 = David
Checking Reference Equality
Example
using System;
public class Demo {
public static void Main(string[] args) {
string str1 = new string("Hello".ToCharArray());
string str2 = new string("Hello".ToCharArray());
string str3 = string.Intern(str1);
string str4 = string.Intern(str2);
Console.WriteLine("str1 == str2: " + (str1 == str2));
Console.WriteLine("ReferenceEquals(str1, str2): " + ReferenceEquals(str1, str2));
Console.WriteLine("ReferenceEquals(str3, str4): " + ReferenceEquals(str3, str4));
}
}
The output of the above code is −
str1 == str2: True ReferenceEquals(str1, str2): False ReferenceEquals(str3, str4): True
Practical Usage Example
Example
using System;
public class Demo {
public static void Main(string[] args) {
string str1 = "50";
string str2 = "100";
Console.WriteLine("String1 = " + str1);
Console.WriteLine("String2 = " + str2);
str2 = string.Intern(str1);
Console.WriteLine("System reference of String1 = " + str2);
}
}
The output of the above code is −
String1 = 50 String2 = 100 System reference of String1 = 50
Key Benefits
-
Memory optimization − Identical strings share the same memory location.
-
Faster reference comparisons − You can use
ReferenceEquals()for quick string comparisons. -
Automatic for literals − String literals are automatically interned by the compiler.
Conclusion
The string.Intern() method retrieves or adds a string to the intern pool, ensuring that identical strings share the same memory reference. This is useful for memory optimization and enables faster reference equality checks when working with frequently used strings.
