Home > Plug-in Development > How to get the declaring element (declaration) from a reference using DXCore

How to get the declaring element (declaration) from a reference using DXCore

August 29th, 2011

Once you have a reference to an element and would like to get its declaration, simply call the GetDeclaration() method of a reference of the Expression type (all references have the Expression base type).

Imagine that we would like to get a field declaration from the property declaration:

private string _Name;
public string Name
  get {  return _Name;  }

Let’s open up the Expression Lab tool window and check the source code structure:

DXCore Code sample inside the Expression Lab

We can see that the field has the Variable type, and the reference inside the getter of the property has the ElementReferenceExpression type. Our method to get the declaration of the Variable type may look like this:

Variable GetPropertyVariable(Property property)
  if (property == null)
    return null;

  // obtain the getter of the property...
  Get getter = property.Getter;
  if (getter == null)
    return null;

  // find the return statement inside the getter...
  Return returnStatement = getter.FindChildByElementType(LanguageElementType.Return) as Return;
  if (returnStatement == null)
    return null;

  // find the reference returned from the getter...
  Expression returnExpression = returnStatement.Expression;
  ElementReferenceExpression targetExpression = returnExpression as ElementReferenceExpression;
  if (targetExpression == null)
    targetExpression = returnExpression.FindChildByElementType(LanguageElementType.ElementReferenceExpression) as ElementReferenceExpression;
  if (targetExpression == null)
    return null;

  // get the reference's declaration...
  return targetExpression.GetDeclaration(true) as Variable;

Now, if we pass the Property declaration to the GetPropertyVariable method, it will return the field declaration of the Variable type. To get an active Property element, you may use the DXCore SourceModel service, for example.

Products: DXCore
Versions: 11.1 and up
VS IDEs: any
Updated: Aug/30/2011
ID: D109

Similar Posts: