Search code examples
c#resharper-7.1resharper-plugins

Delete IProperty from IClass using Resharper 7.1 plugin


I want to create a resharper plugin that removes properties with return type string from a class. I already created a IActionHandler which gets all properties from the selected class, but I don't know how I can modify code structure to remove the properties from the class.

Here is the Execute method of the IActionHandler:

public void Execute(IDataContext context, DelegateExecute nextExecute)
{
    // Fetch active solution from context.
    ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
    if (solution == null)
        return;

    var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
    if (declaredElements == null || declaredElements.IsEmpty())
        return;

    IDeclaredElement declaredElement = declaredElements.First();

    var classElement = declaredElement as IClass;
    if (classElement != null)
    {
        var properties = classElement.Properties.Where(p => p.Type.IsString());

        foreach (IProperty property in properties)
        {
            // Remove IProperty from IClass   <--
        }
    }
}

Any ideas?


Solution

  • I found the answer:

    public void Execute(IDataContext context, DelegateExecute nextExecute)
    {
        // Fetch active solution from context.
        ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
        if (solution == null)
            return;
    
        var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
        if (declaredElements == null || declaredElements.IsEmpty())
            return;
    
        IDeclaredElement declaredElement = declaredElements.First();
    
        var classElement = declaredElement as IClass;
        if (classElement != null)
        {
            // As a class can be declared in multiple files (partial classes) we enumerate all
            // declarations and choose the first one
            var declarations = classElement.GetDeclarations();
            var classDeclaration = declarations.First() as IClassDeclaration;
    
            var properties = classDeclaration.PropertyDeclarations.Where(p => p.Type.IsString());
    
            foreach (var propertyDeclaration in properties)
            {       
                PsiManager.GetInstance(solution).DoTransaction(() =>
                {
                    classDeclaration.RemoveClassMemberDeclaration(propertyDeclaration);
                },
                "PsiTransactionCommand");
            }
        }
    }