Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF do DependencyProperty's cause lots of boxing/unboxing when used with value types?

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));
like image 836
JamesRedcoat Avatar asked Jul 30 '11 16:07

JamesRedcoat


2 Answers

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.

like image 75
ligaz Avatar answered Nov 15 '22 21:11

ligaz


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.

like image 37
Emond Avatar answered Nov 15 '22 20:11

Emond