Get a Tree Node by Reference
What you should know beforehand:
This is useful in case you need to navigate to an element that is referenced by a particular tree node (e.g., from a usage to a declaration).
So, the task is to obtain the reference you need. For example, we want to create a navigation from a particular expression to a declaration (the example is quite useless as it duplicates ReSharper's functionality, nevertheless, it perfectly illustrates the usage of references).
Let's make this as an extension method for
Now, it can be used to navigate to the first referenced element of the tree node under the caret (it would be always a declaration):
We use the
GetTreeNodeUnderCaret()method of the
NodeUnderCaretNavigatorclass shown in Get a Tree Node Under Caret.
GetReferencesmethod returns the list of references.
IReferenceinterface provides the
Resolvemethod that allows getting a declared element from a reference.
Note that to prevent conflicts with user input during the navigation, we must obtain the read lock before calculating the node under the caret. This is done by means of the special method of the