Hi Peter,
Yes u r right. But in my case, Two objects 2 be compared are excatly the
same, and when any property is changed in the original object, I need to
identify that object is changed and have to raise some event. And
comparision
is only for 2 object and once or twice for the application.
Please suggest whether reflection will work in this case?
Reflection will always work. The only question is whether it's really the
best way to do something. IMHO, it should be the last resort, used only
when there's no other way to accomplish something. I don't feel that it's
a good general-purpose tool.
It's not really clear to me exactly what you're doing. But some things to
consider: the usual mechanism for detecting property value changes is to
include some code in the property setter that raises an event when the
setter is called. The standard pattern is, if you have a property named
"Foo", then the event would be named "FooChanged".
It sounds as though you expect to check the entire object periodically,
comparing it to another object and if it tests unequal, raising an event.
Even without reflection, that's wasteful since you wind up doing that
comparison regularly, when most of the time it doesn't test unequal (which
is the condition you care about). With reflection it's even worse,
because reflection is a relatively slow way to compare two object
instances.
The other thing is that when you wrote "comparing", Michael and I both
made the assumption that you're trying to do an ordinal comparison. From
your most recent post, it seems that you simply care about equality. So,
while I still recommend doing the comparison without reflection, it
probably makes more sense to override the Object.Equals() method rather
than implementing IComparable.
Of course, I think the best way is to forget this whole comparison stuff
altogether and just raise the event from the property setters.
So, to sum up, here's the ranking of possibly implementations, from best
to worst:
1) raise the event from the property setters
2) poll the objects, overriding and using Object.Equals() to test for
equality
3) poll the obejcts, using reflection to traverse the class members,
comparing each one by one
As you can see, your proposed solution is the worst one. You can use it
if you want, and it will probably work. But there are better choices you
could make.
Pete