One option is to parse your string as "C # Script", an experimental version of C # that allows you to declare top-level declarations. Performance:
var tree = SyntaxTree.ParseText("void Foo() {}", options: new ParseOptions(kind: SourceCodeKind.Script));
Gives you a valid syntax tree containing CompilationUnitSyntaxdeclarations of a single method.
source
share