@manhng

Welcome to my blog!

IEquatable

March 1, 2021 22:39

IEquatable (edit)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
/// <summary>
/// https://www.codeproject.com/Articles/20592/Implementing-IEquatable-Properly
/// </summary>
class Program
{
static void Main(string[] args)
{
var point1 = new Point()
{
Name = "point 1",
X = 1,
Y = 1,
Z = 1
};

var point2 = new Point()
{
Name = "point 1",
X = 1,
Y = 1,
Z = 1
};

Console.WriteLine(point1.Equals(point2)); //True
Console.WriteLine(point1 == point2); //False

var apoint1 = new APoint()
{
Name = "point 1",
X = 1,
Y = 1,
Z = 1
};

var apoint2 = new APoint()
{
Name = "point 1",
X = 1,
Y = 1,
Z = 1
};

Console.WriteLine(apoint1 == apoint2); //False
Console.WriteLine(apoint1.Equals(apoint2)); //False

Console.ReadLine();
}
}

class APoint
{
public APoint()
{

}

public string Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
}
class Point : IEquatable<Point>
{
public Point()
{

}

public string Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }

public bool Equals(Point other)
{
if (other == null) return false;
return this.Name.Equals(other.Name)
&& this.X.Equals(other.X)
&& this.Y.Equals(other.Y)
&& this.Z.Equals(other.Z);
}

public static bool operator ==(Point point1, Point point2)
{
if (object.ReferenceEquals(point1, point2)) return true;
if (object.ReferenceEquals(point1, null)) return false;
if (object.ReferenceEquals(point2, null)) return false;

return point1.Equals(point2);
}

public static bool operator !=(Point point1, Point point2)
{
if (object.ReferenceEquals(point1, point2)) return false;
if (object.ReferenceEquals(point1, null)) return true;
if (object.ReferenceEquals(point2, null)) return true;

return !point1.Equals(point2);
}
}
}

Categories

Recent posts