tags:

views:

58

answers:

5

Hi,

I have the following code:

Type type = typeof(T);

foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
    Type dataType = type.GetProperty(pi.Name).GetType();
    object oldValue = type.GetProperty(pi.Name).GetValue(originalVals, null);
    object newValue = type.GetProperty(pi.Name).GetValue(newVals, null);

    if (oldValue != newValue)
    {
        // Do Something
    }
}

The 2 variables originalVals and newVals that I am using are Linq2Sql classes. If 1 has an int field (intField) with an id of 999 and the other has the same field with the same value the oldValue != newValue comparison will pass because it will, obviously, use reference equality.

I'd like to know how to cast oldValue and newValue as the Type stored in dataType, something like:

((typeof(dataType)oldValue); or
(dataType)oldValue;

but this isn't working. Any suggestions?

+2  A: 

For objects, the == and != operators just check if the references are the same: do they point to the same object?

You want to use the .Equals() method to check for value equivalence.

if (!oldvalue.Equals(newvalue))
{
    //...
}
Joel Coehoorn
Yeah, the references are different. I thought .Equals() checks for reference equality too...?
Fermin
.Equals() will _fall back on_ reference equality by default, which is different. Though you might be right in this case that this will be what happens.
Joel Coehoorn
[continued] in which case you might be stuck using the 'MakeGenericType()` method to build an EqualityComparer<T> object to do the compare.
Joel Coehoorn
A: 

use if(!oldValue.Equals(newValue)) or if(!Object.Equals(oldValue, newValue)) instead of !=

Lee
Cheers, if(!Object.Equals(oldValue, newValue)) seems to have done the trick! Thanks.
Fermin
A: 

You can check if they implement the IComparable interface and use that to do the comparison.

IComparable comparable = newValue as IComparable;
if(comparable.CompareTo(oldValue) != 0)
{
    //Do Stuff
}
Geoff
A: 

Try:

Convert.ChangeType(oldValue, dataType)

This should cast oldValue to the type represented by dataType.

Dave Swersky
A: 

I think you need to do this first of all

Type dataType = type.GetProperty(pi.Name).PropertyType;

This will give you the type of the data for the property. What you have is getting you a type for the instance of PropertyInfo.

epitka