I have a class named Point that overloading "==" and "!=" operators to compare two Point object. How can I compare my Point object with "null", this a problem because when I call == or != operator with null a problem inside Equals method. Please open a console application and see what I want to say.How can I fix it.
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static bool operator == (Point p1,Point p2)
{
return p1.Equals(p2);
}
public static bool operator != (Point p1, Point p2)
{
return !p1.Equals(p2);
}
public override bool Equals(object obj)
{
Point other = obj as Point;
//problem is here calling != operator and this operator calling this method again
if (other != null)
{
if (this.X == other.X && this.Y == other.Y)
{
return true;
}
return false;
}
else
{
throw new Exception("Parameter is not a point");
}
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point { X = 9, Y = 7 };
Point p2 = new Point { X = 5, Y = 1 };
p1.X = p2.X;
p1.Y = p2.Y;
bool b1=p1==p2;
Console.ReadKey();
}
}