DFENS
DFENS

Reputation: 319

Compare property values with Reflection

I am trying to build the most budget of ORMs.

I have 2 objects, one "item" and one "original", when creating item, i simply save a COPY of it, in a variable called original. The copy is created via an extension i stole from this post https://stackoverflow.com/a/11308879/10647851

So i want to build my update query, very simple i thought.

foreach (PropertyInfo prop in properties) {
   var one = prop.GetValue(original, null);
   var typeOne = one.GetType();
   var two = prop.GetValue(item, null);
   var typeTwo = two.GetType();

   if(one != two) { ... }
}

However, one is unequal to two in several cases where you would not expect it.

The ID (type in the model = int?) 2703 is unequal to 2703. I stepped through the code and the type is Int32. Booleans are problems too. Strings work. DateTime?'s work.

Upvotes: 2

Views: 2571

Answers (1)

Jorge Córdoba
Jorge Córdoba

Reputation: 52123

Use

if(!object.Equals(one, two)) { ... }

for equality comparison instead. That will invoke the default equality comparator or the overridden one for those types that have implemented it (which includes all value types like int on your example).

!= uses reference equality and therefore produces the same value when the referenced types are exactly the same instance. Using != will give you unexpected results due to the fact you are using GetValue which returns an object.

public object GetValue(object obj)

because one and two are actually reference types (i.e. they are boxed ints instead of value types) the "==" comparator performs a reference equality check.

Upvotes: 2

Related Questions