Bob
Bob

Reputation: 1061

Execute a string and retrieve result

I have this string in a XML File :

DateTime.ParseExact("21/06/1980", "dd/MM/yyyy", 
                     System.Globalization.CultureInfo.GetCultureInfo("fr-fr"))

I would like read the xml, execute this string and retrieve the result.

Do you have any ideas for executing and retrieving the result please?

Upvotes: 1

Views: 89

Answers (3)

user111013
user111013

Reputation:

When your application is compiled, your code is turned into MSIL, which is what is then run on the .NET Framework.

What you're asking for is to compile arbitrary C# Code at run-time, and then execute it.

There's a few possible approaches, but none of them are particularly easy.

The closest thing to easy is if you can take a dependency on having the .NET SDK being present on the environment you're running. If so, then you could call the CSharp Compiler (csc), produce a DLL, and then load it.

However, be careful - this generated code will have all the same rights and abilities as your own code.

In addition, you'll likely run into issues with the same assembly names being loaded multiple times in the same Application Domain.

Upvotes: 0

Amirshk
Amirshk

Reputation: 8258

C# has no such feature. However you can try compiling a dll at runtime, loading it and executing it.

This forum has such an example. The basic idea is using CodeDom.

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351506

Neither C# nor the .NET framework offer any kind of string to code evaluation. If you could guarantee the format of the string (in other words you could guarantee that the string will describe a static method call with three parameters) you could parse out the type, method, and arguments and call them with reflection.

Can you describe the more general problem? Perhaps there is a better approach.

Upvotes: 2

Related Questions