简体   繁体   中英

Strings, being reference types behaving like value types

        string s1 = "hi";
        string s2 = "hi";
        bool x = (s1 == s2);
        Console.WriteLine(bool.Parse(""+x)); //printed as true and my point of interest
        x = s1.Equals(s2);
        Console.WriteLine(bool.Parse("" + x));//printed as true
        s1 = s2;
        x = (s1 == s2);
        Console.WriteLine(bool.Parse("" + x));//printed as true
        x = s1.Equals(s2);
        Console.WriteLine(bool.Parse("" + x));//printed as true  

Since s1==s2 compares references, it shoukd be returned as false. But i get the output as true. I observe this in case of strings alone. When this is done on objects of other classes, it rightly evaluates to false. Why is this exceptional behaviour observed in strings?

There are two things going on here.

The first is that the string type overloads the == operator. The reference comparison of the == operator is only the default behavior. Any type can overload that operator to get better semantics. If you want to guarantee reference equality, use the ReferenceEquals() method.

The second is something called interning , which allows two different string variables that have the same value to refer to the same object. Interning means that even without the overloaded == operator, if the "hi" literal is interned for both variables, the == and ReferenceEquals() comparisons could still return true

Since s1==s2 compares references

That's a false assumption. You can overload the == operator to do whatever you want.

Here is how you can overload it for your own classes, just like String does.

public class Foo
{
    public int Value { get; set; }
    public static bool operator ==(Foo first, Foo second)
    {
        return first.Value == second.Value;
    }
}

MSDN string

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references (7.9.7 String equality operators). This makes testing for string equality more intuitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM