views:

27

answers:

3

Hi all

I've written some code to test equality between column values in DataTables when the column type isn't known.

Testing directly like this:

row["Foo"] == row["Bar"]

always results in false, presumably because object's implementation of Equals uses ReferenceEquals.

So I've resorted to:

row["Foo"].ToString() == row["Bar"].ToString()

This works (at least for the cases I've encountered so far), but it seems a little, well, manky.

Can anyone think of a reason I shouldn't do it this way, or suggest a better way? Remember I don't know the column types at design time, so casting is not an option.

Thanks

David

+1  A: 

row["Foo"].Equals(row["Bar"]) ?

Andrey
You're comparing if both object have the same reference, right?
Bruno Costa
@NazGul if just comparing.
Andrey
This is the same (correct) answer as Quartermeister's. I marked his as correct because I couldn't tell which was first and it was higher up the page. Sorry!
David
@David actually i was first, but nevermind :) i am not too determined amount extra 15 points
Andrey
+1  A: 

Try row["Foo"].Equals(row["bar"]).

When you compare objects using == and there is no predefined or user-defined == operator, C# will compare them using reference equality. If you want to call the Equals method, you need to write it out as a method call.

Quartermeister
Yes, this works! Thank you!
David
A: 

why not use Equals if they are string.

row["foo"].ToString().Equals(row["Bar"].ToString());
prashant
Why not use == which is what I'm already doing?
David