.NET == and .Equals() + More Ways to Compare Correctly in .NET — Definitive Guide

Because .NET behaves very strangely here

Arnold Abraham
CodeX

--

Image Made by the Author via Canva

Object-oriented programming languages allow you comparisons, whatever the type. Sadly, .NET does it a bit weirdly and follows strange rules.

This doesn’t make comparisons straightforward and predictable. While the == operator acts as expected, calling it differently might get weird results.

In .NET, there are many ways to compare. Better read on to determine which does the correct job for your operation. Otherwise, you could suffer a nasty surprise…

There’s More than One Way to Compare

.NET offers you different comparison variants:

  1. Using the == operator
  2. In System.Object, there’s an Equals() method
  3. Also, the statically defined Equals() method on System.Object
  4. Using ReferenceEquals from System.Object
int integer1 = 17;
int integer2 = 17;
object integer3 = integer1;

var equal0 = integer1 == integer2;
var equal1 = (object)integer1 == integer3;
var equal2 = integer1.Equals(integer2);
var equal3 = object.Equals(integer1, integer3);
var equal4 = object.ReferenceEquals(integer1, integer2);
var…

--

--

Arnold Abraham
CodeX
Writer for

JavaScript, TypeScript and C#/.NET Tutorials/News/Best Practices by a German Software Engineer - Fun helps you to learn on the fly --> arnoldcode.com