Dynamic code execution at run-time?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is there a way dynamically execute a a piece of code at run-time in C#? Such
as representing a custom method "UserInfo.GetEmail()" as a string and get
'evaluated" during execution and return it's value? this method represents an
already existing method in my app.

I'm trying to avoid creating a large hard-coded switch statement and would
like to control what methods are called dynamically from a database table for
different scenarios.
 
Just on a more general note ... I think code generation may be overkill in
your case .. it sounds to me like you could handle this with a factory and a
few handler objects.

Cheers,

GReg
 
Another option would be to introduce some delegates. This may or may
not, depending on your needs (generally delegates are used for groups
of functions with the same signature).

Using a switch method you might specify the function via a string or
enumeration (FunctionName = "SomeFunction";) and of course, use a
switch to call the appropriate function. Using a delegate means that
you can set the actual function to a variable in the same manner that
you assign a number to an int.

//We define a delegate type which specifies return type and signature.
//(The type is named "VoidFunction" with not params or return)
delegate void VoidFunction();
//We create an instance of this type.
VoidFunction MyFunctionPointer;
//We store some function in the variable.
MyFunctionPointer = this.SomeFunction();
//If we have a function stored...
if(MyFunctionPointer != null)
//we can call it via the variable's name.
MyFunctionPointer();

As you can see, you need to know the signature ahead of time and
functions with different signatures need to be stored in different
delegates of different types.

As stated, using reflection, you can use the MethodInfo class in a
similar, function-pointer-like manner, and if there are arguments, they
can be stored in an array. This is more flexible, but requires much
more overhead that using delegates.

System.Type MyType = this.GetType();
System.Reflection.MethodInfo MyFunctionPointer;
//Get a "pointer" to the function AppleSauce()
MyFunctionPointer = MyType.GetMethod("AppleSauce");
//Paremeters can be stored in an array:
Object[] Params = new Object[]{1, "SomeString"};
//The function can be called later...
MyFunctionPointer.Invoke(this, Params);
 
Back
Top