2

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?

F Chopin
  • 574
  • 7
  • 23
  • 1
    C# or C# Script ? – Fildor Sep 01 '21 at 09:59
  • 1
    https://stackoverflow.com/questions/475033/detecting-programming-language-from-a-snippet https://learn.microsoft.com/en-us/dotnet/api/microsoft.csharp.csharpcodeprovider?redirectedfrom=MSDN&view=net-5.0 – Henrique Mauri Sep 01 '21 at 10:04
  • Maybe have a look into https://learn.microsoft.com/en-us/archive/msdn-magazine/2016/january/essential-net-csharp-scripting and also https://www.cs-script.net/ – Fildor Sep 01 '21 at 10:06

1 Answers1

0

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

Kendar
  • 692
  • 7
  • 25