Friday, 12 February 2016

c# - What is the difference between String.Intern and String.IsInterned?



MSDN states that




String.Intern retrieves the system's
reference to the specified String




and





String.IsInterned retrieves a
reference to a specified String.




I think that IsInterned should have returned (I know it doesn't) a bool stating whether the specified string is interned or not. Is that correct thinking ? I mean it is atleast not consistent with .net framework naming convention.



I wrote the following code:




    string s = "PK";
string k = "PK";

Console.WriteLine("s has hashcode " + s.GetHashCode());
Console.WriteLine("k has hashcode " + k.GetHashCode());
Console.WriteLine("PK Interned " + string.Intern("PK"));
Console.WriteLine("PK IsInterned " + string.IsInterned("PK"));


The output is :




s has hashcode -837830672



k has hashcode -837830672



PK Interned PK



PK IsInterned PK



Why is string.IsInterned("PK") returning "PK"?



Answer



String.Intern interns the string if it's not already interned; String.IsInterned doesn't.



IsInterned("PK") is returning "PK" because it's already interned. The reason for it returning the string instead of a bool is so that you can easily get a reference to the interned string itself (which may not be the same reference as you passed in). In other words, it's effectively returning two related pieces of information at once - you can simulate it returning bool easily:



public static bool IsInternedBool(string text)
{
return string.IsInterned(text) != null;
}



I agree that the naming isn't ideal, although I'm not sure what would have been better: GetInterned perhaps?



Here's an example showing that difference though - I'm not using string literals, to avoid them being interned beforehand:



using System;

class Test
{
static void Main()

{
string first = new string(new[] {'x'});
string second = new string(new[] {'y'});

string.Intern(first); // Interns it
Console.WriteLine(string.IsInterned(first) != null); // Check

string.IsInterned(second); // Doesn't intern it
Console.WriteLine(string.IsInterned(second) != null); // Check
}

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...