== Operator (C# Reference)

The equality operator == returns true if its operands are equal, false otherwise.

Value types equality

Operands of the built-in value types are equal if their values are equal:

int a = 1 + 2 + 3;
int b = 6;
Console.WriteLine(a == b);  // output: True

char c1 = 'a';
char c2 = 'A';
Console.WriteLine(c1 == c2);  // output: False
Console.WriteLine(c1 == char.ToLower(c2));  // output: True


For relational operators ==, >, <, >=, and <=, if any of the operands is not a number (Double.NaN or Single.NaN) the result of operation is false. That means that the NaN value is neither greater than, less than, nor equal to any other double (or float) value. For more information and examples, see the Double.NaN or Single.NaN reference article.

Two operands of the same enum type are equal if the corresponding values of the underlying integral type are equal.

By default, the == operator is not defined for a user-defined struct type. A user-defined type can overload the == operator.

Beginning with C# 7.3, the == and != operators are supported by C# tuples. For more information, see the Equality and tuples section of the C# tuple types article.

String equality

Two string operands are equal when both of them are null or both string instances are of the same length and have identical characters in each character position:

string s1 = "hello!";
string s2 = "HeLLo!";
Console.WriteLine(s1 == s2.ToLower());  // output: True

string s3 = "Hello!";
Console.WriteLine(s1 == s3);  // output: False

That is case-sensitive ordinal comparison. For more information about how to compare strings, see How to compare strings in C#.

Reference types equality

Two other than string reference type operands are equal when they refer to the same object:

public class ReferenceTypesEquality
    public class MyClass
        private int id;

        public MyClass(int id) => this.id = id;

    public static void Main()
        var a = new MyClass(1);
        var b = new MyClass(1);
        var c = a;
        Console.WriteLine(a == b);  // output: False
        Console.WriteLine(a == c);  // output: True

The example shows that the == operator is supported by user-defined reference types. However, a user-defined reference type can overload the == operator. If a reference type overloads the == operator, use the Object.ReferenceEquals method to check if two references of that type refer to the same object.

Operator overloadability

User-defined types can overload the == operator. If a type overloads the equality operator ==, it must also overload the inequality operator !=.

C# language specification

For more information, see the Relational and type-testing operators section of the C# language specification.

See also