N
Neven Klofutar
hi,
I have some questions regarding overriding Equals method so I can use it on
my objects.
1) When overriding Equals method, do I have to check all fields for
"equality" or just the ones I want to use to distinct my objects ? As far as
I know, only the ones I want to use to distinct my object by ... field
"Name" in the example bellow.
2) What does a method GetHashCode() do exactly, and do I have to put all of
my fields in it or just fields I want to use to distinct my objects by ?
Thanx, Neven
---------------------
public class Person {
string _Name = "";
string _Phone = "";
public string Name {
get {return _Name;}
set {_Name = value;}
}
public string Phone {
get {return _Phone;}
set {_Phone = value;}
}
public override bool Equals(Object obj) {
if (obj == null || GetType() != obj.GetType()) return false;
Person person = (Person)obj;
return _Name == person.Name && _Phone == person.Phone;
}
public override int GetHashCode() {
return _Name.GetHashCode() ^ _Phone.GetHashCode();
}
}
I have some questions regarding overriding Equals method so I can use it on
my objects.
1) When overriding Equals method, do I have to check all fields for
"equality" or just the ones I want to use to distinct my objects ? As far as
I know, only the ones I want to use to distinct my object by ... field
"Name" in the example bellow.
2) What does a method GetHashCode() do exactly, and do I have to put all of
my fields in it or just fields I want to use to distinct my objects by ?
Thanx, Neven
---------------------
public class Person {
string _Name = "";
string _Phone = "";
public string Name {
get {return _Name;}
set {_Name = value;}
}
public string Phone {
get {return _Phone;}
set {_Phone = value;}
}
public override bool Equals(Object obj) {
if (obj == null || GetType() != obj.GetType()) return false;
Person person = (Person)obj;
return _Name == person.Name && _Phone == person.Phone;
}
public override int GetHashCode() {
return _Name.GetHashCode() ^ _Phone.GetHashCode();
}
}