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?
From the docs for the ==
operator:
For predefined value types, the equality operator (
==
) returnstrue
if the values of its operands are equal,false
otherwise. For reference types other thanstring
,==
returnstrue
if its two operands refer to the same object. For thestring
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With