Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - Parse string to MethodDeclarationSyntax

Tags:

roslyn

Is there any function in Roslyn, by which I can parse my string as a MethodDeclarationSyntax?

I have a file which contains the method declaration, so I am reading that file content to string and now I want to create a Method from that string. Any suggestions?

like image 398
Pratik Mehta Avatar asked Aug 10 '26 18:08

Pratik Mehta


1 Answers

One option is to parse your string as "C# Script", an experimental version of C# that allows top-level method declarations. Doing:

var tree = SyntaxTree.ParseText("void Foo() {}", options: new ParseOptions(kind: SourceCodeKind.Script));

Gives you a valid syntax tree that contains a CompilationUnitSyntax of a single method declaration.

like image 197
Jason Malinowski Avatar answered Aug 13 '26 16:08

Jason Malinowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!