The1nk The1nk - 1 month ago 7
C# Question

DataGridViewCell Type mismatch, when GetType().Name matches?

When iterating over a collection of

s in a
, I was testing for equality of a specific cell like so:

var transactionLogId = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value;
if (dgvRow.Cells[0].Value == transactionLogId) {
// Snip

And to my dismay, it never entered the nested block. Though both equal the same (
), and both
, it doesn't work unless I append a
to both sides of the equality check.

Curious as to what I'm missing here. Thanks!


Operators are static calls, which means that overload resolution will resolve based strictly on the operand's compile time types.

In your case, overload resolution is resolving to following operator overload:

==(object, object)

because those are the types of the operands. The == for objects simply performs a reference equality check, tha is, if both objects are the same object, which they clearly are not.

The same happens in the following code:

object o1 = 1;
object o2 = 1;
var equal = o1 == o2; //false

Using Equals in this case is the correct thing to do here, as it is virtual call and it will give you the correct result.

Then why does this work when you call ToString() on both operands? Simply because the overload resolution resolves to the ==(string, string) overload implented in the string class which performs value equality.