Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5534

c# Object Comparison fails

I have two objects of type SqlServer.Smo.Column. If I try to compare one property of both

ColumnaOrigen.Properties["DataType"].Value != ColumnaDestino.Properties["DataType"].Value

It return true even both values are numeric.

In the debugger the type showed is object{string}; the same happens with other datatypes such as object{bool}

  1. Why does this happen?

  2. How can I compare those values to get the right answer?

Upvotes: 0

Views: 65

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157098

1- Why this happens ?

Because you are not comparing values of the variables, but their references. Since both variables are object, == calls Object.ReferenceEquals.

2- How can I do to compare those values to get the right answer ?

If both types are string, cast them and compare them as strings.

string a = ColumnaOrigen.Properties["DataType"].Value as string;
string b = ColumnaDestino.Properties["DataType"].Value as string;

if (!string.Equals(a, b))
{ }

Upvotes: 4

Related Questions