I found an interesting thing, take this as a C# program:
namespace ConsoleApplication1
{
using System;
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public override bool Equals(object comparedStudent)
{
Student stu = comparedStudent as Student;
if (stu == null)
{
return false;
}
return ID.Equals(stu.ID) && Name.Equals(stu.Name);
}
public override int GetHashCode()
{
return ID.GetHashCode() ^ Name.GetHashCode();
}
/// <summary>
/// Notice that this will cause NullPointException……Why?
/// If I use "return s1.ID==s2.ID && s1.Name==s2.Name", that'd be OK.
/// </summary>
public static bool operator ==(Student s1, Student s2)
{
return s1.Equals(s2);
}
public static bool operator !=(Student s1, Student s2)
{
return !s1.Equals(s2);
}
}
public class Program
{
static void Main(string[] args)
{
Student s1 = new Student();
s1.ID = 1;
s1.Name = "YourName";
Student s2 = new Student();
s2.ID = 1;
s2.Name = "YourName";
//Why there's an exception here (NullPoint exception)
bool isSame = (s1 == s2);
Console.WriteLine(isSame);
}
}
}
If you copy my codes and run, a NullPointer exception will be thrown out. Why?
PS:If I use "return s1.ID==s2.ID && s1.Name==s2.Name" in the overload operator +, that'd be OK.
Why? I'm using net4.0 VS2015.
And if you debug by dropping the debug point at "bool isSame = (s1 == s2);" You'll soon find it enters into the "==" overload function 3 times, and in the end, s1 and s2 are null!