Introduction
In this article, we are going to discuss how equality works with reference type and value type.
Prerequisites
Basic understanding of class and structure in C#.
How does equality work with Reference Type and Value Type?
The first question that comes to mind is, what is a reference type and value type?
Value Type
In value type, the data value is stored in its own memory address. Eg int i= 500.
Examples of value types are structure, int, char, bool, decimal, etc.
Reference Type
In reference type, it stores points of the memory location where the data values are stored.
Eg. string str = “Hello Kirtesh”
An example of a reference type is a class.
Equality for Value Type and Reference Type
Now we will discuss how equality works with a reference type.
Let’s discuss the below code to understand how equality works with reference type (Class) and structure type (Structure),
Reference type Equality
We will use ==, Equal(), or System.Object.ReferenceEquals() for reference and value equality check.
- System.Object.ReferenceEquals(): method is used to check if specific object instances are the same instance or not.
- ==: Used to check if both objects point to the same location.
- Equal(): Method used for ReferenceEquals().
Let’s understand all three concepts using the below example.
public class Member
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
class Program
{
static void Main(string[] args)
{
Member obj1 = new Member
{
Id = 1,
Name = "Kirtesh",
Address = "Vadodara"
};
Member obj2 = new Member
{
Id = 1,
Name = "Kirtesh",
Address = "Vadodara"
};
Console.WriteLine("***Two Objects with same Values****");
Console.WriteLine(obj1 == obj2);
Console.WriteLine(obj1.Equals(obj2));
Console.WriteLine(System.Object.ReferenceEquals(obj1, obj2));
Console.ReadLine();
}
}
Output

In the above example, obj1 and obj2 have the same values and different memory locations, and the result is false because it is doing reference equities, not value comparisons.




Join the conversation! Your thoughts help the community grow.