Overriding Equals

  • Thread starter Thread starter Frank Wisniewski
  • Start date Start date
F

Frank Wisniewski

Is this suppose to work like this:


I have a class called foo in which I tried to override equals and return
different answers based on what was passed in.

public class foo
{
private string _name;

public string Name
{
get
{
return _name;
}
}

public override bool Equals(object obj)
{
if (obj is string)
{
string tempStr = (string)obj;
return this._name.Equals(tempStr);
}

if (obj is foo)
{
foo tempfoo = (foo)obj;
return tempfoo.Name.Equals(this._name);
}

return false;
}

}


if I have an arraylist of foo objects and call the Contains method with a
string object as the parameter, the Equals method on the foo class is never
called. If I pass it a foo object, it all works as planned. Is there some
rule that say the parameter for the Equals method must be the same type as
the class Equals is based on?

Just curious.

Thanks
 
...
if I have an arraylist of foo objects and call the
Contains method with a string object as the parameter,
the Equals method on the foo class is never
called. If I pass it a foo object, it all
works as planned. Is there some rule that
say the parameter for the Equals method must
be the same type as the class Equals is based on?

Nope, but as you use a string object as the argument, it's the string.Equals
that will be used.

The other way around would work, with an ArrayList of strings, where you
could pass a foo instance.

// Bjorn A
 
Back
Top