C # Equality Operator

From https://msdn.microsoft.com/en-us/library/d5x73970.aspx

When applying class T restrictions: Avoid == and! = Operators in the type parameter, because these operators will be for reference identity only, not for equality of values. This is true even if these statements are overloaded in the type that is used as the argument. The following code illustrates this point; the output is false, even if the String class overloads the == operator.

public static void OpTest<T>(T s, T t) where T : class { System.Console.WriteLine(s == t); } static void Main() { string s1 = "target"; System.Text.StringBuilder sb = new System.Text.StringBuilder("target"); string s2 = sb.ToString(); OpTest<string>(s1, s2); } 

Everything is fine until I tried to follow, with the same method

 static void Main() { string s1 = "target"; string s2 = "target"; OpTest<string>(s1, s2); } 

It outputs "True", s1 and s2 refer to different objects in memory, even if they have the same value? Did I miss something?

+6
source share
1 answer

Strings are interned in .NET, so when you do

 string s1 = "target"; string s2 = "target"; 

they both point to the same object. This is why the MSDN example uses StringBuilder , it tricks the CLR into creating another string object with the same value so that the statement test in the general method returns false.

+7
source

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


All Articles