Understanding C#'s `String.IsInterned()` Method: Optimizing String Comparisons and Memory Usage

Learn how to leverage C#'s `String.IsInterned()` method for efficient string comparisons and memory management. This tutorial explains the string intern pool, demonstrates the use of `IsInterned()`, and highlights its role in improving application performance by reusing existing string references.



Understanding C#'s `String.IsInterned()` Method

The C# `String.IsInterned()` method checks if a given string is already present in the string intern pool. The intern pool is a cache of string references in memory. Using the intern pool can improve performance in situations where you are comparing many strings.

How `String.IsInterned()` Works

The `IsInterned()` method searches the intern pool for a string with the same value as the one you provide. If it finds an identical string, it returns a reference to that string in the pool. If no match is found, it returns `null`. Unlike `String.Intern()`, `IsInterned()` does *not* add the string to the pool if it's not already there.

`String.IsInterned()` Method Signature


public static string IsInterned(string str);

The method takes a string (`str`) as input and returns a string reference (if found in the intern pool); otherwise, `null`.

Example 1: Checking for Interned Strings


string str1 = "Hello";
string internedStr = string.Intern(str1); // Adds "Hello" to the intern pool (if not already there)
string result = string.IsInterned(str1); // result will be a reference to the interned string
Console.WriteLine(result);

Example 2: Comparing Interned and Non-interned Strings


string a = new string(new char[] { 'a' });
string b = new string(new char[] { 'b' });
string.Intern(a); // Intern string 'a'
Console.WriteLine(string.IsInterned(a) != null); // True
Console.WriteLine(string.IsInterned(b) != null); // False

`String.Intern()` vs. `String.IsInterned()`

The key difference is that `Intern()` adds a string to the intern pool if it's not already there, while `IsInterned()` only checks for existence—it doesn't add strings.