Introduction
ReferenceEquals and
Equals and == are pretty much does the same thing.
- It compares the object reference to SAME instance.
- Even if the object reference is of the same type and have same value it returns false.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var c1 = new Car(1, "Matiz");
var c2 = new Car(1, "Matiz");
//COMPARES OBJECT REFERENCES OF DIFFERENT INSTANCES OF SAME TYPE
Console.WriteLine(c1.Equals(c2));//false
Console.WriteLine(ReferenceEquals(c1, c2));//false
Console.WriteLine(c1 == c2);//false
var c3 = c2;
//COMPARES OBJECT REFERENCES OF SAME INSTANCES OF SAME TYPE
Console.WriteLine(c3.Equals(c2));//true
Console.WriteLine(ReferenceEquals(c3, c2));//true
Console.WriteLine(c3 == c2);//true
Console.Read();
}
private class Car
{
private readonly int _id;
private readonly string _name;
public Car(int id, string name)
{
_id = id;
_name = name;
}
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var c1 = new Car(1, "Matiz");
var c2 = new Car(1, "Matiz");
//COMPARES OBJECT REFERENCES OF DIFFERENT INSTANCES OF SAME TYPE
Console.WriteLine(c1.Equals(c2));//false
Console.WriteLine(ReferenceEquals(c1, c2));//false
Console.WriteLine(c1 == c2);//false
var c3 = c2;
//COMPARES OBJECT REFERENCES OF SAME INSTANCES OF SAME TYPE
Console.WriteLine(c3.Equals(c2));//true
Console.WriteLine(ReferenceEquals(c3, c2));//true
Console.WriteLine(c3 == c2);//true
Console.Read();
}
private class Car
{
private readonly int _id;
private readonly string _name;
public Car(int id, string name)
{
_id = id;
_name = name;
}
}
}
}
No comments :
Post a Comment