In WPF do DependencyProperty's cause lots of boxing/unboxing when used with value types? Or does the implementation some how to prevent this and not box/unbox value types? Is so how do they do this?
I think value types are a major use case for DependencyPropertys.
Thanks
public double Price
{
get { return (double)GetValue(PriceProperty); }
set { SetValue(PriceProperty, value); }
}
public static readonly DependencyProperty PriceProperty =
DependencyProperty.Register("Price", typeof(double), typeof(Quote), new UIPropertyMetadata(0.0d));
The short answer is yes.
The underlining storage for dependency property values does not have a notion of value types and stores everything as object, which will cause boxing. The framework itself uses a 'clever trick' for Boolean properties storage optimization via a helper class BooleanBoxes, which has true and false values stored as boxed objects.
In general if you have a few custom properties you have nothing to worry about. However if you have a complex scene that has thousands of your custom dependency objects flying around you may want to think about boxing/unboxing performance optimizations.
In addition to the other answers:
When WPF reads or changes a dependency property (binding and animation) it does NOT use these setters and getters. So the (un)boxing you are showing in the code will not be executed.
These setters and getters you are showing are for us, developers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With