2

Is it possible to execute code from a string variable, like:
string mystring = "Console.WriteLine(\"Hi\");"; Is it possible to execute the contents of mystring (printing 'Hi')?

  • 1
    With questions like this it's a good idea to explain why you want this behavior since it's clearly not common. By doing so there is a chance someone may suggest a more elegant solution that produces the more specific behavior you're trying to achieve. – Spencer Ruport Feb 01 '11 at 05:10
  • Actually, I'd quite like an answer to this also. I've been thinking for a while about writing an Python prompt style thing for C# using reflection or similar. I know that some exist, but using one which has been written already isn't really a great learning exercise - one of the reasons I refuse to use any libraries outside of .net in my applications - I like to learn things myself. – dotalchemy Feb 01 '11 at 05:16

4 Answers4

4

It's possible using the System.Reflection.Emit or System.CodeDom namespaces, but it's not exactly a good idea as there's no mechanism to control what namespaces are and are not allowed. A user could build a string that would wipe your hard drive.

eval()-like functions are huge gaping security holes and should be avoided. The preferred alternative is a DSL (domain specific language).

Joel Coehoorn
  • 380,066
  • 110
  • 546
  • 781
1

Yes. Fire up the compiler at runtime and pass in your code. It will spit out executable code. See the System.CodeDom namespace, especially, System.CodeDom.Compiler.

jason
  • 228,647
  • 33
  • 413
  • 517
1

Use the Code DOM

H.B.
  • 142,212
  • 27
  • 297
  • 366
Pierreten
  • 9,569
  • 6
  • 36
  • 44
1

Need to use reflection to get something like that. C# is not dynamic or interpreted language, so you dont get it out of the box

http://www.codeproject.com/KB/dotnet/Expr.aspx

How can I evaluate C# code dynamically?

Community
  • 1
  • 1
Sarwar Erfan
  • 17,864
  • 5
  • 44
  • 57