I am learning WPF and there’s a piece of code which I don’t quite understand the method declared with constraints:
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class // Need help to interpret this method declaration
I understand this is a shared method and T has be a class but what is what is ‘static T FindAncestor’? Having troubles interpreting it as a whole. Thanks!
Code:
public static class VisualTreeHelperExtensions
{
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class // Need help to interpret this method
{
DependencyObject target = dependencyObject;
do
{
target = VisualTreeHelper.GetParent(target);
}
while (target != null && !(target is T));
return target as T;
}
}
The
statickeyword in front means that you do not have to instantiateVisualTreeHelperExtensionsin order to call theFindAncestormethod. You can say:Where
myObjis aDependencyObject. Thewhere, as you said, makes sure thatT(MyClassin this case) is indeed a classFor convenience, Methods like this can be declared like this:
Which would allow you to call the method like so:
Effectively adding a method to your
DependencyObjectafter the fact.