Search code examples
c#operator-overloadingvalue-typereference-type

Why we can apply == (Equality Operator) on value type(like int) in C#?


Equality operator (==) is a reference type and we all know that Int32 is a struct which means that is a value type. I also checked the inside of the Int32 and I couldn't find any Operator Overloading related to Equality Operator (==).

So, my question is why can we apply == on Int32?

I also checked the decimal type and I noticed that it has some Operator Overloading, so naturally we can use == on decimal types.

enter image description here


Solution

  • Per the equality operators documentation for value types:

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

    Also, be aware that

    User-defined struct types don't support the == operator by default. To support the == operator, a user-defined struct must overload it.

    So, in a nutshell all user-defined structs must define the equality operator to overload it. But all built-in value types don't need to, it "just works".