What is the difference between String.Intern and String.IsInterned?

MSDN declares that

String.Intern retrieves the system reference to the specified string

and

String.IsInterned retrieves the link to the specified string.

I think IsInterned should have returned (I know it is not) bool, indicating whether the specified string is interned or not. Is that the right way of thinking? I mean that it at least is not consistent with the .net 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"));

Output:

s hashcode -837830672

k has hashcode -837830672

PK Interned PK

PK IsInterned PK

Why does string.IsInterned ("PK") return "PK"?

+3
source share
1 answer

String.Intern , ; String.IsInterned .

IsInterned("PK") "PK", . , bool, , ( , ). , - , bool:

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

, , , : GetInterned ?

, : , :

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
    }
}
+17

Source: https://habr.com/ru/post/1716927/


All Articles