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.
User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types. If == is overloaded, != must also be overloaded.
using System; class Test { public static void Main() { // 1. Numeric equality: Console.WriteLine((2 + 2) == 4); // 2. Reference equality: two objects, same boxed value object s = 1; object t = 1; Console.WriteLine(s == t); // 3. String equality: same string value, different string objects string a = "hello"; string b = new string("hello"); // compare string values Console.WriteLine(a == b); // compare string references Console.WriteLine((object)a == (object)b); } }
True False True False
C# Operators | CLR 7.9 Relational operators | != Operator