Overriding Equals

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
 
B

Bjorn Abelli

...
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top