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?
source share