user566552
user566552

Reputation: 81

Program code as a string

This is not really for practical use, but is there any way to execute a string as a program code in C#?

For example :
instead of writing

Console.WriteLine("blah blah blah");

I would like to write something like

string s = "Console.WriteLine(\"blah blah blah\")"
execute(s);

Upvotes: 1

Views: 170

Answers (5)

Joel Coehoorn
Joel Coehoorn

Reputation: 415860

It is possible in C#, but it is intentionally difficult. There's no simple "exec()" function you can use out of the box.

AFAIK this is by design. Exec functions are big gaping security holes, because they expose the full power of the language to users who often should not have that power. As the programmer, you often intend to use an exec() function to allow a user to enter simple math or string expressions, and suddenly you have a hacker come along and instantiate a System.Net.WebClient and use it to download and execute something much more malicious. There is no way to limit which assemblies are allowed.

The preferred alternative in .Net languages is something called a Domain Specific Language (DSL). A DSL is a (relatively) easy way to define your own grammar (and the meaning behind it) for what kinds of things you want to allow the user to do, without the security implications of giving them access to the whole base class library. It also has the advantage of allowing you to provide specialized operations at a higher level than they might otherwise be available.

Upvotes: 1

Jalal Said
Jalal Said

Reputation: 16162

This can be done using Microsoft.CSharp.CSharpCodeProvider.

Check this.

Upvotes: 0

Olaf
Olaf

Reputation: 10247

I know it's not exactly what you asked for (although you didn't mention a the language of the program in the string), but IronPython is very cool: http://secretgeek.net/host_ironpython.asp, http://blogs.msdn.com/b/abhinaba/archive/2006/02/09/528416.aspx.

Also (as boca already mentioned) runtime compilation worked well, too: Is it possible to dynamically compile and execute C# code fragments?

Upvotes: 1

svick
svick

Reputation: 244837

You can do this using CodeDOM. See Using the CodeDOM at MSDN.

Upvotes: 0

boca
boca

Reputation: 2352

The only way I can think of doing this is by compiling your code at runtime. Here is an article that explains how to do this http://simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/

Upvotes: 1

Related Questions