Parsing embedded expressions in Roslyn

c#, razor, roslyn

Solution

You need to call `CSharpSyntaxTree.ParseText()`, and pass a `CSharpParseOptions` with `SourceCodeKind.Interactive`, which allows top-level expressions.

Problem

I am trying to write a parser for a QML-like markup language and I would like to allow C# expressions in the markup. So an example might look like this: ``` ClassName { Property1: 10 Property2: Math.Sqrt(123) Property3: string.Format("{0} {1}", "Hello", "World") } ``` (This is also somewhat like ASP.NET's Razor engine but afaics Razor doesn't use Roslyn?) How would I do this? I want to parse only a single expression, whether that be a literal, a method call, a lambda etc. I've tried using `CSharpSyntaxTree.ParseText` but that expects a whole file and I can't find any documentation that seems to relate to this use-case.

Original source