Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of UncommonField<T> in WPF

Tags:

c#

wpf

I just relfected over WindowsBase.dll >> System.Windows.UncommonField<T> and I wondered about the usage of this class... E.g. it's used in the Button-class:

public class Button : ButtonBase
{    
    private static readonly UncommonField<KeyboardFocusChangedEventHandler> FocusChangedEventHandlerField = new UncommonField<KeyboardFocusChangedEventHandler>();
}

So what is the use of this "wrapper"?

like image 665
HerpDerpington Avatar asked Aug 09 '13 18:08

HerpDerpington


1 Answers

Short answer

It's used to lower memory usage.

Longer answer

Let's start with dependency properties. On each DependencyObject, a large number of dependency properties can be defined. Whether it's a "local" DependencyProperty such as TextBox.Text or an attached one like Grid.Row, most of them aren't ever set and only keep their default value. In order to avoid having each DependencyObject instance taking kilobytes of memory by storing a value for each defined dependency property, only values being different from the defaults are kept inside the instance.

Now meet the internal UncommonField<T> class. You can view it as a lightweight DependencyProperty without any metadata, coercion or property change notification. However, it uses the same mechanism as a real DependencyProperty regarding its value: it has to be different from the default to be stored inside the DependencyObject. Since the KeyboardFocusChanged event is rarely used (explaining the uncommon adjective), it makes sense to save a little memory here.

But you're probably not Microsoft writing a framework having to account for thousands of DependencyObject instances and optimize for a few bytes. Simply replace a static UncommonField<T> someField by an instance T someField.

like image 162
Julien Lebosquain Avatar answered Oct 06 '22 05:10

Julien Lebosquain