Runtime  Compile C# Code

Runtime Compile C# Code

Well have you ever wondered to write the C# code in string and execute them? I was thinking that since a long time ago and was able to do some research recently and tried it out using C# Console App. And guess what, I figured it out recently. For this, you must have a nuget package “Microsoft.CodeAnalysis.CSharp.Scripting” and “Microsoft.CodeAnalysis.CSharp”.

var code = "(5 + 3).ToString()";
var run = await CSharpScript.RunAsync(code, ScriptOptions.Default);
var result = (string)run.ReturnValue;
Console.WriteLine(result);

Try this one in your console application and you will be able to get the result “8”. I tried it and it really worked. Here is the github gist you can look at it and try it on your side as well.

Here is the link to the github gist . Happy Coding! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *