0

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;
    }
}

4 Answers 4

1

The static keyword in front means that you do not have to instantiate VisualTreeHelperExtensions in order to call the FindAncestor method. You can say:

VisualTreeHelperExtensions.FindAncestor<MyClass>(myObj);

Where myObj is a DependencyObject. The where, as you said, makes sure that T (MyClass in this case) is indeed a class

For convenience, Methods like this can be declared like this:

public static T FindAncestor<T>(this DependencyObject dependencyObject)
  where T : class // Need help to interpret this method declaration

Which would allow you to call the method like so:

myObj.FindAncestor<MyClass>();

Effectively adding a method to your DependencyObject after the fact.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the comprehensive explanation.
1

The T is a placeholder for a type - what is known as a generic. The where clause is a generic constraint that requires reference types.

Comments

1

Hope I understand your question.

It's a declaration of public static function.

If it's not you're asking for, please explain better.

Comments

1

It means that it is a static method (you can call it without an instance of the class created) that returns an object of type T. FindAncestor is the name of the method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.