Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic types equality operator

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

When applying the where T : class constraint, avoid the == and != operators on the type parameter because these operators will test for reference identity only, not for value equality. This is the case even if these operators are overloaded in a type that is used as an argument. The following code illustrates this point; the output is false even though 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 ok until i tried following, with same method

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

It outputs 'True', s1 and s2 reference different objects in memory even they have same value right? Am i missing something?

like image 686
Ahmet Sancar Avatar asked Mar 09 '15 22:03

Ahmet Sancar


1 Answers

Strings are interned in .NET, so when you do

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

they are both pointing to the same object. This is why the MSDN example uses a StringBuilder, this fools the CLR into creating another string object with the same value so that the operator test in the generic method will return false.

like image 58
Erik Avatar answered Oct 10 '22 04:10

Erik