views:

83

answers:

2

I have a class with a Property called 'Value' which is of type Object. Value can be of any type, a structure, a class, an array, IList etc.

My problem is with the setter and determining whether the value has changed or not. This is simple enough for value types, but reference types and lists present a problem.

For a class, would you assume that the Equals method has been implemented correctly, or just assume that the value has changed every time the setter is called? If I did assume it's changed, then perhaps I should assume it for value types as well, so that the behaviour is consistent.

For a list, I could check the size and then every item in the collection to see if they have changed.

How do you guys handle this problem?

+4  A: 

Instead of having

object Value

you could declare

IEquatable<T> Value

This way you know that all instances of Value will implement the Equals method. Thus you can check equality of two instances.

Manu
+4  A: 

Why should you care whether the value has changed or not? Is there a reason why you can't just assume the value changed every time the setter is called?

If there is a good technical reason why, you could always use generics and make your Value of type IEquatable<T> instead of type object. This ensures that the object has implemented the Equals() method.

Dan Herbert
Hi, thanks for both answers regarding IEquatable<T>, though I don't want to place this restriction on Value. The only reason I care about if the value has changed is because a ValueChanged event is raised. To be honest, I don't really care at all, so I'll just assume it's changed every time the setter is called!
Jules
Your reasoning makes sense, however I wouldn't go so far as to check the value of your property every time the setter is called. You'd suffer both in terms of performance and understandability. I think most programmers would expect the "`ValueChanged`" event to happen every time Value is set, not just when it is set with a new value.
Dan Herbert