Introduction
In some cases of real development time, we are required to check the equality, either its for value or reference.
When we compare two string values or any primitive type, then it means we are going to test value equality. This is also known as equivalence.
When we will compare two reference types, (string, object, class), then it means we are going to compare its reference equality.
In this article, I will explain both.
As we know, in C# we have 2 types:
- Value Type
- Reference Type
Based on that, C# provides 3 things to compare value type and reference type:
- ==,
- Equal()
- ReferenceEquals()
== operator
It is used to compare object reference equality. If the type is reference, it is by default, but when the value is immutable, it means its value will not be changed. Then it's overloading the operator and comparing its value.
ReferenceEquals()
If we required to check for reference then we could use ReferenceEquals.
It is a static method and takes two parameters both must be a reference type.
Also, it is not throwing any exception kind of a NullReferenceException
public static bool ReferenceEquals(Object? objA, Object? objB);
Equal()
It is a C# method that returns a boolean value based on compare
public virtual bool Equals (object? obj);
public static bool Equals(Object? objA, Object? objB);
- object o1 = null;
- object o2 = new object();
- Console.WriteLine("object o1 = null;");
- Console.WriteLine(" object o2 = new object();");
- // Return true
- Console.WriteLine("ReferenceEquals(o1, o1) : ", ReferenceEquals(o1, o1));
- // Return true
- Console.WriteLine("ReferenceEquals(o2, o2): ", ReferenceEquals(o2, o2));
- // Return false
- Console.WriteLine("ReferenceEquals(o1, o2): ",ReferenceEquals(o1, o2));
- // Return false
- Console.WriteLine("ReferenceEquals(o2, o1): ", ReferenceEquals(o2, o1));
- // Return throw NullReferenceException
- Console.WriteLine("o1.Equals(o1): ", o1.Equals(o1));
- // Return throw NullReferenceException
- Console.WriteLine("o1.Equals(o2);: ", o1.Equals(o2));
- // Return false
- Console.WriteLine("o2.Equals(o1): ", o2.Equals(o1));
- // Return false
- Console.WriteLine("o2.Equals(o2): ", o2.Equals(o2));

In this output window, you can check the result.
Now let's try with more examples for clarification.
== operator is used to check the reference.


Join the conversation! Your thoughts help the community grow.