Check if a string contains valid C# code programatically in C#

Viewed 98

I have a string that contains C# code. How can I check that the C# code in the string is valid C# and doesn't contain build errors?

I'd like to do this programmatically in C#.

I don't expect the code in the string to contain references to other code outside of the string, so it's not necessary to load up the whole project or solution, only the code in the string needs to be considered.

Can I use the Roslyn Api or something similar?

1 Answers

You can compile it,e.g. with this approach: https://www.kendar.org/?p=/dotnet/sharptemplate you can find it even on WaybackMachine :P It's a library i wrote some years ago.

An example of what you need is the following:

    const string dllName = "CompileClassTemplate";
    const string resultDllName = "CompileResultingTemplate";
    var path = TestUtils.GetExecutionPath();
    var source = ResourceContentLoader.LoadText("ClassTemplate.cs", Assembly.GetExecutingAssembly());

    var pp = new SharpParser();
    var sharpClass = pp.ParseClass(source, "TestParserClass", "SharpTemplate.Test.Resources.Parsers");

    var loadedAssembly = BuildParserClass(dllName, path, sharpClass);

Here is the SharpTemplate Nuget and the Git repo

Related