why does ReferenceEquals(s1,s2) returns true

前端 未结 5 1433
遥遥无期
遥遥无期 2021-01-07 23:52
  String s1 = \"Hello\";
  String s2 = \"Hello\";

Here s1, s2 are different but then why ReferenceEquals() is returning true

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-08 00:03

    if you google "ReferenceEquals string"

    you'll get this

    The following was the accepted answer from the link, in case link dies

    In this example "obj1" and "obj2" are separate instances, Right ?

    No - strings are reference-types, and obj1 and obj2 are two variables pointing to the same instance, due in-part to something called interning; basically, any string literal in an assembly* can share the same string reference. This is possible only because strings are immutable. You can also check for interned strings (string.IsInterned), and manually intern if you want (string.Intern).

    When two strings have same value, are they sharing same instance ?

    They might have the same instance; but it isn't guaranteed. Strings that have been generated on-the-fly won't normally be interned; for example, the only ones that share references here are 2 & 4:

    string tmp1 = "aa", tmp2 = "aaa";

    string s1 = new string('a', 5),

    s2 = "aaaaa",

    s3 = tmp1 + tmp2,

    s4 = "aaaaa";

    Console.WriteLine(ReferenceEquals(s1, s2));

    Console.WriteLine(ReferenceEquals(s1, s3));

    Console.WriteLine(ReferenceEquals(s1, s4));

    Console.WriteLine(ReferenceEquals(s2, s3));

    Console.WriteLine(ReferenceEquals(s2, s4));

    Console.WriteLine(ReferenceEquals(s3, s4));

    *=strictly: net-module

提交回复
热议问题