k80sg
k80sg

Reputation: 2473

Code syntax explaination help

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

Upvotes: 0

Views: 229

Answers (4)

Michael Hays
Michael Hays

Reputation: 6908

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.

Upvotes: 1

Charles Boyung
Charles Boyung

Reputation: 2481

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.

Upvotes: 1

Tigran
Tigran

Reputation: 62265

Hope I understand your question.

It's a declaration of public static function.

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

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191037

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.

Upvotes: 1

Related Questions