I have a property changed callback and in it i need to perform some validation.
I am going to take a new value and validate it against a set of other property criteria such as min and max values.
To do this I am planning to either take the dependency object from the changed event and use
DependencyObject.SetValue(TargetProperty,NewValue);
or cast it to a variable and use the properties directly
ObjectType myObjectType = (ObjectType)DependencyObject;
myObjectType.Target=NewValue;
My question is what would be the reasons for using either method over the other. Would casting be more of a drain on resources than say lots of SetValue/GetValue lookups etc? I will be referencing properties up to 10 times in the methods.
Many thanks.
The standard implementation of a dependency property in a DependencyObject
is to call SetValue()
. Furthermore, casting is dirt cheap, especially in this context. So there's really no practical difference between the two approaches.
For me, it would come down to what part of the operation you want to focus on. If you want your implementation tied closely to the fact that the object is in fact a DependencyObject
, I can't see much reason to avoid calling SetValue()
directly. That's what WPF does.
On the other hand, if you want the code to be more C#-like and follow normal property accessor idioms, casting to the correct type and then setting the property directly will be more readable and maintainable. Yes, it adds the extra operations of casting and then calling the property setter. But those are negligible costs, practically immeasurable. And in return, you get code that doesn't assume any particular implementation of the property.