Is there a way to dynamically execute code contained in a string using .net 2.0, in a similar way to eval() in javascript or using sp_executeSQL in tsql?
I have a st
While you could use an enumeration to indicate the action you want to take, or use CodeDom to emit code dynamically, what it comes down to is that you want to define a transformation of some kind, which means that you have inputs, and an output.
Figuring out the output is easy in this case, you have a string. For the inputs, it would seem like you can have a variable number of inputs. That would be defined as an IEnumerable
.
With that in mind, you can define an interface like so:
public interface IStringManipulation
{
string Manipulate(IEnumerable parameters);
}
Then, it would be easy to define implementations of this type and then place the type names in your config.
You really want to do this instead of dynamically compiling code from strings. In using strings, you have a great deal of flexibility, yes, but you have no compile time checking, and are opening yourself up to bugs and security issues.
Also, the time it is going to take to write a piece of code to emit code based on the string fragment you provide is going to be quite tedious as well, as you have to build the assembly, the class, the method, then compile, and then call the method you compile dynamically through reflection (unless you have it implement an interface, in which case, you might as well do what I'm suggesting anyways).