• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

C#, Calling a procedure with a paramter (Replacing case statement)

I am currently calling a procedure based on a paramter from a database table where I am having to use a case statement.   In this manner I am having hard code my procedures with a case statement.  Please refer to the example:

CreateMe(string ProcedureName)
{
switch(ProcedureName)
  case "FirstProc":
           FirstProc();
           break;
    case "SecondProc":
           SecondProc();
           break;
    etc.
}

I am wanting to be ablle to perform the same process but without having to hardcode (case statement) so that it can then be driven by the database.

Any ideas please....

Thanks!
0
vandy02
Asked:
vandy02
3 Solutions
 
Gautham JanardhanCommented:
can u explain a bit more depending on the ProcedureName u call different functions  FirstProc();
SecondProc();
 etc rt ?
and u want to generalize it
0
 
NeotkCommented:
You can do it with Reflection. Take a read in this article:

http://my.execpc.com/~gopalan/dotnet/reflection.html

Regards, Rodrigo Leote
0
 
Bob LearnedCommented:
Here is a clean and simple example:

using System;
using System.Reflection;

public class Reflect
{

    public static object ExecuteMethod(string name, params object[] parameters)
    {
        Assembly assy = Assembly.GetExecutingAssembly();
        string ns = assy.GetType().Namespace;

        MethodInfo method = assy.GetType().GetMethod(ns + "." + name);
        return method.Invoke(null, parameters);
    }

}

Bob
0
 
andrewjbCommented:
..or have a lookup dictionary...

delegate void TargetFn();

Dictionary<string,TargetFn> lookup;

// populate once at startup
lookup = new Dictionary...
lookup["FirstProc"] = FirstProc;
etc.


Then, call via:

lookup[ProcedureName]();


Magic :-)

(Give or take tests to check the procedureName is valid etc. ANd you can then change your key to be whatever you like - doesn't need to be the procedure name.)
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now