Class behaves properly using overridden Equals and GetHashCode methods
using System;
using System.Collections;
public class GoodCompare {
public static void Main() {
Name president = new Name ("A", "B");
Name first = new Name ("C", "D");
Console.WriteLine("The hash codes for first and president are: ");
if (president.GetHashCode() == first.GetHashCode())
Console.WriteLine("equal");
else
Console.WriteLine("not equal");
}
}
public class Name {
protected String first;
protected char initial;
protected String last;
public Name(String f, String l) {
first = f;
last = l;
}
public Name(String f, char i, String l) : this(f,l) {
initial = i;
}
public override String ToString() {
if (initial == '\u0000')
return first + " " + last;
else
return first + " " + initial + " " + last;
}
public override bool Equals(Object o) {
if (!(o is Name))
return false;
Name name = (Name)o;
return first == name.first && initial == name.initial
&& last == name.last;
}
public override int GetHashCode() {
return first.GetHashCode() + (int)initial
+ last.GetHashCode();
}
}
Related examples in the same category