Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How To Compare 2 Object Properties On A Class
Message
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01474360
Message ID:
01474409
Views:
56
>Because they can hold any type.
>
>>Why do you define them as public properties and of type object? Does Object implement IComparable interface? I doubt it, I think you need to use specific type for these properties.
>>
>>>I have this class:
>>>
>>>
>>>public class ReportColumn
>>>{
>>>    public string ColumnName { get; set; }
>>>    public object OriginalValue { get; set; }
>>>    public object ChangedValue { get; set; }
>>>    public bool IsChanged { get; private set; }
>>>
>>>    public void SetIsChanged()
>>>    {
>>>        IsChanged = false;
>>>
>>>        PropertyInfo[] sourceProperties = OriginalValue.GetType().GetProperties();
>>>        foreach (PropertyInfo pi in sourceProperties)
>>>        {
>>>            object originalProperty = OriginalValue.GetType().GetProperty(pi.Name).GetValue(this, null);
>>>            object changedProperty = ChangedValue.GetType().GetProperty(pi.Name).GetValue(comparisonObject, null);
>>>
>>>            IsChanged = (originalProperty != changedProperty);
>>>
>>>            if (IsChanged)
>>>            {
>>>                break;
>>>            }
>>>        }
>>>    }
>>>}
>>>
>>>
>>>
>>>I'm trying to set IsChanged, but the SetIsChanged method doesn't seem right. I want to compare the values of the OriginalValue and ChangedValue properties.
>>>
>>>What's the right way to do this?

I think you meant to use:
object originalProperty = OriginalValue.GetType().GetProperty(pi.Name).GetValue(OriginalValue, null);
object changedProperty = ChangedValue.GetType().GetProperty(pi.Name).GetValue(ChangedValue, null);
But, even assuming the two objects are of the same type, that still won't work because you are comparing objects and the default behaviour of == is to return reference equality (i.e. it will only be true if the objects being compared are the same instance)

This should work (but I haven't tried it):http://www.dbones.co.uk/blog/post/2008/02/Using-reflection-to-test-for-equality.aspx

However if the object types in question are of your own making (and there are not too many) I'd consider implementing an override of the == operator.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform