1

I register for a callback notification on a DependencyProperty of type MyObject. In the function, I do a cast from DependencyObject to my expected type of MyObject. Will this ever return null? Can I safely remove the null check from my code?

private static void OnMyObjectChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    MyObject obj = d as MyObject;
    if (obj != null) // Is this check needed?  Will it ever be null?
    {
        ...
    }
}
Chromozon
  • 295
  • 2
  • 3
  • 8
  • Can you have a static dependency object? I don't know if it can, but I know that is a common situation with WeakEvents, that uses null to represent a static source. – Scott Chamberlain Feb 24 '16 at 21:14

1 Answers1

3

What you probably mean is this:

private static void OnMyObjectChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var obj = d as MyObject;
    if (obj != null)
    {
        ...
    }
}

As long as this is not a PropertyChangedCallback of an attached property (which might by applied to DependencyObjects of any derived type), it is safe to directly cast the DependencyObject parameter to your object type. It is the callback of your property, and WPF never calls it for any other property.

So just write:

private static void OnMyObjectChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var obj = (MyObject)d;
    ...
}
Clemens
  • 123,504
  • 12
  • 155
  • 268