0

Does anyone know if there is a way to evaluate c# code at runtime. eg. I would like to allow a user to enter DateTime.Now.AddDays(1), or something similar, as a string and then evaluate the string to get the result.

I woder if it is possible to access the emmediate windows functionality, since it seems that is evaluates every line entered dynamically.

I have found that VB has an undocumented EbExecuteLine() API function from the VBA*.dll and wonder if there is something equivalent for c#.

I have also found a custom tool https://github.com/DavidWynne/CSharpEval (it used to be at kamimucode.com but the author has moved it to GitHub) that seems to do it, but I would prefer something that comes as part of .NET

Thanks

1

5 Answers 5

1

Mono has the interactive command line (csharp.exe)

You can look at it's source code to see exactly how it does it's magic:

https://github.com/mono/mono/raw/master/mcs/tools/csharp/repl.cs

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

Comments

1

As you've probably already seen, there is no built-in method for evaluating C# code at runtime. This is the primary reason that the custom tool you mentioned exists.

I also have a C# eval program that allows for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com, for additional details.

Comments

0

Microsoft's C# compiler don't have Compiler-as-a-Service yet (Should come with C# 5.0).

You can either use Mono's REPL, or write your own service using CodeDOM

Comments

0

Its not fast but you can compile the code on the fly, see my previous question,

Once you have the assembly and you know the type name you can construct an instance of your compiled class using reflection and execute your method..

Comments

0

The O2 Platform's C# REPL Script Environment use the Fluent# APIs which have a real powerful reflection API that allows you do execute code snippets.

For example:

"return DateTime.Now.ToLongTimeString();".executeCodeSnippet(); 

will return

5:01:22 AM

note that the "...".executeCodeSnippet(); can actually execute any valid C# code snippet (so it is quite powerful).

If you want to control what your users can execute, I could use AST trees to limite the C# features that they have access to.

Also take a look at the Microsoft's Roslyn, which is VERY powerful as you can see on Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio)

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.