Runtime Compile C# Code

Runtime Compile C# Code

Well have you ever wondered to write the C# code in string and execute them? In this blog I will tell you how to Runtime Compile C# Code. 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 *

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site
%d bloggers like this: