Using equal operators in C#

= is assignment, like in

var i = 5;

Do not use this operator in the if statement.

== is for comparison like in

if(i == 6){...}

there is no === operator in C#


(The following is somewhat of a "comment" but is too long to be in a comment and would be lost with the other comments in this post.)

In C# == (like all operators in C#) is non-polymorphic. That is, the "version" of == that is called is always based on the static type at compile-time.

For instance:

object a = Guid.NewGuid();
object b = new Guid(""+a);
a == b // false -- uses object.== -- an *identity* compare

The Equals virtual method, on the other hand, is defined on object and is thus polymorphic across all sub-types.

object a = Guid.NewGuid();
object b = new Guid(""+a);
a.Equals(b) // true -- uses Guid.Equals

The choice of which one to use (== or Equals) is sometimes subtle -- but important. Most collection types will use Equals for tasks like Contains, etc. (This is pretty much required for all generic containers as there is no T.== for an arbitrary type T.)

// compile-time error: Operator '==' cannot be applied to operands of type 'T' and 'T'
bool equals<T> (T a, T b) { return a == b; }

// fair-game, because object defines Equals and it's polymorphic to subtypes
bool equals<T> (T a, T b) { return a.Equals(b); }

See When should I use == and when should I use Equals? and Guidelines for Implementing Equals and the Equality Operator (==), etc. Personally, I use == over Equals for statically-resolvable concrete types for which == is well-defined and I will not (by contract or convention) deal with a subtype -- examples are string and (most) structure types (e.g. int, Guid).

Happy coding.

Edit: There is no C# === operator (as people have said, duh!). If talking about the JavaScript variant, it would be approximately:

bool trippleEquals (object a, object b) {
  return a.GetType() == b.GetType() && a.Equals(b);
}

(It is strict equality in JavaScript -- but not object identity).

If talking about object identity then it should be the same as (object)a == (object)b which has the same semantics as object.ReferenceEquals(a,b).


a single = is for assignment like:

String myString = "Hi There";

A double equal is for comparison

if (5 == 5)
{
    do something
}

triple equals in some languages mean exactly equal.

C# does not utilize that operator.

Tags:

C#