Roslyn Structural Duplication is a small .NET console tool that demonstrates structural C# code transformation with the Roslyn compiler APIs.
The project reads a C# source file, parses it into a syntax tree, finds method declarations that have exactly one parameter, duplicates that parameter, assigns the duplicated parameter a derived name, formats the modified tree, and writes the result to Output.cs.
Text-based source-code changes are fragile because C# syntax can vary widely across formatting styles, modifiers, attributes, generic types, nested classes, and expression-bodied methods.
This project solves that problem by using Roslyn's syntax tree model instead of string replacement. It shows how to safely inspect and rewrite C# source structure with compiler-aware APIs.
It is useful as a learning project or starting point for:
- C# source-to-source transformation
- Roslyn syntax tree traversal
- Automated refactoring experiments
- Static analysis tooling
- Code generation prototypes
- Understanding
CSharpSyntaxRewriter
- Language: C#
- Runtime: .NET 9
- Project type: Console application
- Compiler platform: Roslyn
- Main packages:
Microsoft.CodeAnalysis.CSharpMicrosoft.CodeAnalysis.CSharp.Workspaces
- Formatting:
Microsoft.CodeAnalysis.Formatting.Formatter - Build system: .NET SDK / MSBuild
- Accepts a C# source file path as a command-line argument.
- Parses source code with
CSharpSyntaxTree.ParseText. - Traverses code using
CSharpSyntaxRewriter. - Detects
MethodDeclarationSyntaxnodes with exactly one parameter. - Duplicates the existing parameter structurally.
- Generates a new parameter name:
namebecomesname2name2becomesname3count9becomescount10param007becomesparam8
- Preserves trivia from the original identifier.
- Formats the transformed syntax tree.
- Writes the transformed file to
Output.cs.
.
├── RoslynStructuralDuplication.sln
├── README.md
└── RoslynStructuralDuplication/
├── RoslynStructuralDuplication.csproj
├── Program.cs # Roslyn rewriter and CLI entry point
└── Input.cs # Sample input file with transformation cases
dotnet buildFrom the solution root:
dotnet run --project RoslynStructuralDuplication -- RoslynStructuralDuplication/Input.csThe transformed file is written to:
Output.cs
Input:
class Test
{
static void Ping(string host) => Console.WriteLine(host);
}Output:
class Test
{
static void Ping(string host, string host2) => Console.WriteLine(host);
}The rewriter currently targets only MethodDeclarationSyntax nodes with exactly one parameter.
It does not transform:
- Constructors
- Local functions
- Methods with zero parameters
- Methods with two or more parameters
Because this is a structural transformation demo, some duplicated parameters can require additional semantic handling before the output compiles. For example, duplicating params, out, or default-valued parameters may need extra rules depending on the final refactoring goal.