Static Method Code Action: Listing 2
Full GetEdit Method Implementation
Listing 2: StaticMethodCodeAction GetEdit Function
public ICodeActionEdit GetEdit(System.Threading.CancellationToken cancellationT
{
var syntaxTree = (SyntaxTree)_document.GetSyntaxTree(cancellationToken);
var firstToken = _methodDeclaration.GetFirstToken();
var firstTokenTrivia = firstToken.LeadingTrivia;
var formattedMethodDeclaration = _methodDeclaration.ReplaceToken(
firstToken, firstToken.WithLeadingTrivia(Syntax.TriviaList()));
var staticToken = Syntax.Token(firstTokenTrivia, SyntaxKind.StaticKeyword);
var newModifiers = Syntax.TokenList(
new[] { staticToken }.Concat(formattedMethodDeclaration.Modifiers));
var newMethodDeclaration = formattedMethodDeclaration.Update(
formattedMethodDeclaration.Attributes,
newModifiers,
formattedMethodDeclaration.ReturnType,
formattedMethodDeclaration.ExplicitInterfaceSpecifierOpt,
formattedMethodDeclaration.Identifier,
formattedMethodDeclaration.TypeParameterListOpt,
formattedMethodDeclaration.ParameterList,
formattedMethodDeclaration.ConstraintClauses,
formattedMethodDeclaration.BodyOpt,
formattedMethodDeclaration.SemicolonTokenOpt);
var formattedLocalDeclaration = CodeActionAnnotations.FormattingAnnotation
.AddAnnotationTo(newMethodDeclaration);
var tree = (SyntaxTree)_document.GetSyntaxTree();
var newRoot = tree.Root.ReplaceNode(_methodDeclaration,
formattedLocalDeclaration);
return _editFactory.CreateTreeTransformEdit(_document.Project.Solution,
syntaxTree, newRoot, cancellationToken: cancellationToken);
}
About the Author
Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].