473,385 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Dynamic code execution at run-time?

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.


Feb 28 '06 #1
4 3959
What you want to do is called Reflection. Take a look at the
System.Reflection namespace. A common way is to use Type.InvokeMember

http://msdn.microsoft.com/library/de...embertopic.asp

Take a look at the example C# code at the above link. It looks intimidating
at first, but it's actually pretty striaght forward.

"Dave" wrote:
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.



Feb 28 '06 #2
This may be a good case for dynamically compiling a class. Rick Strahl has a
pretty good article here
http://www.west-wind.com/presentatio...ynamicCode.htm

Reflection as mentioned will work, but if this code is called frequently, it
is alot slower.

Greg

"Dave" wrote:
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.



Feb 28 '06 #3
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

"Greg Young" wrote:
This may be a good case for dynamically compiling a class. Rick Strahl has a
pretty good article here
http://www.west-wind.com/presentatio...ynamicCode.htm

Reflection as mentioned will work, but if this code is called frequently, it
is alot slower.

Greg

"Dave" wrote:
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.



Feb 28 '06 #4
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);

Mar 1 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: bry | last post by:
Hi, I'm trying to do a dynamic import of a file that has no problems with it, that is to say I can import it normally, my sys.path is set to the right folder etc. but my dynamic import code is not...
2
by: JC | last post by:
Hello, I'm looking for examples of how to make dynamic creation of code and dynamic execution of the same code. I want to do some code dynamically and then I want to use it to get some results....
0
by: Namratha Shah \(Nasha\) | last post by:
Hey Guys, Today we are going to look at Code Access Security. Code access security is a feature of .NET that manages code depending on its trust level. If the CLS trusts the code enough to...
6
by: dhnriverside | last post by:
Hi peeps, I'm trying to create some controls textboxes at runtime, based on the number of items in a IETreeView that are checked. That I can do, I've got a place holder and I can create the...
8
by: George Meng | last post by:
I got a tough question: The backgroud for this question is: I want to design an application works like a engine. After release, we can still customize a form by adding a button, and source code...
1
by: Kurt | last post by:
If I remember correctly isn't there a way to execute dynamic code in .Net like below? Taking a string variable and executing. "Console.WriteLine("Test");" Thanks Kurt
5
by: alingsjtu | last post by:
Hello, every body. When execute dynamic generated multiple OPENQUERY statements (which linkes to DB2) in SQLServer, I always got SQL1040N The maximum number of applications is already connected...
7
by: Ronald S. Cook | last post by:
I've always been taught that stored procedures are better than writing SQL in client code for a number of reasons: - runs faster as is compiled and lives on the database server - is the more...
6
by: =?ISO-8859-1?Q?Tim_B=FCthe?= | last post by:
Hi, we are building a Java webapplication using JSF, running on websphere, querying a DB2 9 on Suse Enterprise 10. The app uses JDBC and PreparedStatements only (aka dynamic SQL). Every night,...
11
by: Stevo | last post by:
I have a problem with Firefox 2 where if I resize the height of a DIV (using JavaScript), but the rest of the page below isn't being updated to reflect the new positions that affected items should...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.