T
Tony Johansson
Hi!
Assume I have 2 instances of a class called Test see below which will work
as key in a hashtable. The Name property of instance1 is set to 'Paul', and
the Name property of instance2 is set to 'Piet'. Both instances will
generate different hashcode, and they're also different according to the
Equals method.So far so good. When looking up Piet I will get the value
object whatever it can be.
Now, suppose that I change the Name of instance2 to 'Paul', then, according
to my Equals method, both instances should be equal, and according to the
hashcode and equals method will generate the same hashCode(same key) and
that is not allowed
to have in a hashtable..
What is the solution to this senario ?
public class Test
{
string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public override GetHashCode()
{
return Name.GetHashcode();
}
public override Equals(object other)
{
Test myTest = other as Test;
if( myTest == null ) return false;
return this.Name == myTest.Name;
}
}
Assume I have 2 instances of a class called Test see below which will work
as key in a hashtable. The Name property of instance1 is set to 'Paul', and
the Name property of instance2 is set to 'Piet'. Both instances will
generate different hashcode, and they're also different according to the
Equals method.So far so good. When looking up Piet I will get the value
object whatever it can be.
Now, suppose that I change the Name of instance2 to 'Paul', then, according
to my Equals method, both instances should be equal, and according to the
hashcode and equals method will generate the same hashCode(same key) and
that is not allowed
to have in a hashtable..
What is the solution to this senario ?
public class Test
{
string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public override GetHashCode()
{
return Name.GetHashcode();
}
public override Equals(object other)
{
Test myTest = other as Test;
if( myTest == null ) return false;
return this.Name == myTest.Name;
}
}