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?

3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

This does not 100% answer your question but for all like me who found this and just want to check for valid C# in a string, you could use the Microsoft.CodeAnalysis.CSharp NuGet package:

var tree = CSharpSyntaxTree.ParseText(myString);
if (tree.GetDiagnostics().Any())
  // not valid
else
  // valid

However, this will only check if the syntax is correct. Not if you can actually run it.

Example

Console.WriteLine(myString);

This line would result in no error because it's syntactically correct, but you won't be able to execute it because there is no variable myString. But if you remove the semicolon, the .GetDiagnostics() will tell you that the semicolon is missing at the end of the line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.