== Operator
Visual Studio .NET 2003
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.
expr1 == expr2
Where:
- expr1
- An expression.
- expr2
- An expression.
Remarks
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.
Example
// cs_operator_equality.cs
using System;
class Test
{
public static void Main()
{
// Numeric equality: True
Console.WriteLine((2 + 2) == 4);
// Reference equality: different objects, same boxed value: False
object s = 1;
object t = 1;
Console.WriteLine(s == t);
// Define some string
string a = "hello";
string b = String.Copy(a);
string c = "hello";
// compare string values for a constant and an instance: True
Console.WriteLine(a == b);
// compare string references;
// a is a constant but b is an instance: False
Console.WriteLine((object)a == (object)b);
// compare string references, both constants have the same value,
// so string interning points to same reference: True
Console.WriteLine((object)a == (object)c);
}
}
Output
True False True False True
See Also
C# Operators | 7.9 Relational and type testing operators | != Operator