why does ReferenceEquals(s1,s2) returns true

前端 未结 5 1432
遥遥无期
遥遥无期 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

    0 讨论(0)
  • 2021-01-08 00:09

    This is due to interning - the CLI automatically re-uses strings obtained as literals (i.e. strings that have come directly from your source code). Note that if you did:

    char[] chars = {'h','e','l','l','o'};
    string s1 = new string(chars);
    string s2 = new string(chars);
    

    they would not be the same string instance, as they have not come from literals.

    This is documented against the Ldstr IL instruction:

    The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning").

    0 讨论(0)
  • 2021-01-08 00:18

    Strings are immutable, once it created in the memory following same String objects are refered to the previously created String object for more http://msdn.microsoft.com/en-us/library/362314fe.aspx

    0 讨论(0)
  • 2021-01-08 00:20

    String is immutable so uses same reference for same value Also see Eric lippert blog for all about this

    0 讨论(0)
  • 2021-01-08 00:21

    You also can use String.Copy(String str) static method to create strings that will be different objects

    String s1 = "Hello";
    String s2 = string.Copy("Hello");
    

    then s1 and s2 will be referencing different objects.

    0 讨论(0)
提交回复
热议问题