public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { ConstructorDeclarationSyntax processedDeclaration = (ConstructorDeclarationSyntax)base.VisitConstructorDeclaration(node); // Make the constructor declaration private if it has other access modifier SyntaxTokenList modifiers = processedDeclaration.Modifiers; // Static constructors are different story if (modifiers.Any(SyntaxKind.StaticKeyword)) { return(processedDeclaration); } // If it is already declared as private, do nothing if (!modifiers.Any(SyntaxKind.PrivateKeyword)) { if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword)) { // If there is already access modified, replace it with `private' keyword. // Considers: // public A() {} -> private A() {} // protected A() {} -> private A() {} SyntaxToken accessKeyword = processedDeclaration.GetFirstToken(t => t.Kind == SyntaxKind.PublicKeyword || t.Kind == SyntaxKind.ProtectedKeyword); // Copy leading and trailing trivia SyntaxToken privateKeyword = Syntax.Token(SyntaxKind.PrivateKeyword) .WithLeadingTrivia(accessKeyword.LeadingTrivia) .WithTrailingTrivia(accessKeyword.TrailingTrivia); // Replace the access modifier ConstructorDeclarationSyntax newDeclaration = processedDeclaration.ReplaceToken(accessKeyword, privateKeyword); return(newDeclaration); } else { // Otherwise, insert `private' at the beginning. // Considers: // A() {} -> private A() {} // Copy trivia from first token SyntaxToken firstToken = processedDeclaration.GetFirstToken(); // Copy leading and trailing trivia SyntaxToken privateKeyword = Syntax.Token(SyntaxKind.PrivateKeyword) .WithLeadingTrivia(firstToken.LeadingTrivia) .WithTrailingTrivia(firstToken.TrailingTrivia); // Remove the leading trivia from first token ConstructorDeclarationSyntax newDeclaration = processedDeclaration.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(Syntax.Whitespace(" "))); // Insert the access modifier newDeclaration = newDeclaration .WithModifiers(newDeclaration.Modifiers.Insert(0, privateKeyword)); return(newDeclaration); } } return(processedDeclaration); }