Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of Generics in C#

Tags:

c#

generics

Why does this code prints False?

    class Program
{
    public static void OpTest<T>(T s, T t) where T : class
    {
        Console.WriteLine(s == t);
    }

    static void Main()
    {
        string s1 = "string";
        System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
        string s2 = sb.ToString();
        OpTest(s1, s2);
    }
}

Do I understand correctly that when compared, they are compared not as strings, but as objects, which is why not their values are compared, but the addresses to which they point?

like image 684
Sektor Avatar asked Jul 03 '18 15:07

Sektor


1 Answers

From the docs for the == operator:

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

Since T cannot be guaranteed to be a value type as it's generic, the compiler must assume it is a reference type.

like image 194
DavidG Avatar answered Sep 16 '22 16:09

DavidG