[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Csharp - Dynamically calling a void

Posted on 2011-10-21
10
Medium Priority
?
255 Views
Last Modified: 2012-08-13
Hi

Please forgive some of my .net terminology, hopefully this makes sense

I want to dynamically called a CSharp void (sub procedure etc etc), based on the value in a database

So for instance, lets say VariableA has a value of XYZ. I then want to look up the value of XYZ, and return the void that needs to be excuted, e.g Hello World

Then if ABC is the value, then it would return Goodbye World, and then execute that void

So essentially,execution of the void is all done from 1 line of code, but the void to actually be executed comes from a datanase

I hope that this makes sense. I am pretty sure it is possible, I just have no idea what its called to be able to start a google search

Thanks
0
Comment
Question by:seancurt
  • 5
  • 3
  • 2
10 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37007293
Here's one example:

using System;
using System.Collections.Generic;

namespace _27409039
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Action> functionMap = new Dictionary<string, Action>();

            functionMap.Add("XYZ", HelloWorld);
            functionMap.Add("ABC", GoodbyeWorld);

            string dbValue = "XYZ";

            functionMap[dbValue]();

            dbValue = "ABC";

            functionMap[dbValue]();

            Console.ReadKey();
        }

        static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }

        static void GoodbyeWorld()
        {
            Console.WriteLine("Goodbye World!");
        }
    }
}

Open in new window

0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 37008512
Hello, I think he want something more like:
using System;

namespace Demo
{
    static class Program
    {
        static void Main(string[] args)
        {
            System.Type myType = typeof(Program);

            InvoqueMyMethod(myType, "XYZ");
            InvoqueMyMethod(myType, "ABC");

            Console.ReadKey();
        }

        static void InvoqueMyMethod(System.Type myType, string myMethodName)
        {
              myType.GetMethod(myMethodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, null);
         }

        static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }

        static void GoodbyeWorld()
        {
            Console.WriteLine("Goodbye World!");
        }

    }
}

Open in new window

0
 
LVL 17

Accepted Solution

by:
Carlos Villegas earned 2000 total points
ID: 37008539
Oops sorry, line 10 and 11 must be:
InvoqueMyMethod(myType, "HelloWorld");
InvoqueMyMethod(myType, "GoodbyeWorld");

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 37008562
..... I mean lines 11 and 12.....
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37009232
If you know the function names ahead of time, why use reflection?
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 37009269
Maintenance, simplicity, I think. From the point of view of performance I prefer your example of course.
0
 

Author Comment

by:seancurt
ID: 37013891
Hi

I'll have a play with these, thanks. How do you handle passing parameters too?

Does it just need to be a default of args[] or something ?

I'll let you know how I get on

Thanks
0
 

Author Comment

by:seancurt
ID: 37013935
Hi

I think yv889c's method words best. The reason being that they names of the functions will also be stored in the database (i think) and so being able to provide the string name works best

However....

One issue I seem to have (what you provided works no problem by the way), is that, is there a limitation to the scope that it can "see" ?

I want to call a function that is in a different DLL file.

If in my code i call "HelloWorld" it will only work if it is within the same namespace. If it is in a different namespace, it returns an "object not set" error

Any thoughts ?

Thanks
0
 

Author Comment

by:seancurt
ID: 37013994
Have managed to get it to work.

System.Type myType = typeof(Program); actually needs to be the namespace that the method is in (not sure how I can assign this dynamically at the moment, as it needs a proper type, i need to provide a string

Then within the invoke function, I put this, which seems to work

it doesn't have the binding info that was provided, am not sure what this does to be honest, so will start to read up !

Thanks

            MethodInfo m = myType.GetMethod(myMethodName);
            m.Invoke(null, null);
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 37014209
Hello, to pass parameters to your methods you can use something like this:
static void InvoqueMyMethod(System.Type myType, string myMethodName, params object[] parameters)
{
    myType.GetMethod(myMethodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, parameters);
}

Open in new window


Also, all these examples are based on static methods, if you are going to invoke instance methods the code must be slightly modified.


I have modified the example to show you how to get a Type by its full name, and passing parameters to a method too:
using System;

namespace Demo
{
    static class Program
    {
        static void Main()
        {
            // This get the current assembly that containt the methods that you want to invoke.
            // Also you can load externals assemblys.
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            
            // To get the type that contain the methods that you want to invoke, you must use the full name of the type,
            // Demo is the namespace where is the Program class located, so Demo.Program.
            System.Type myType = myAssembly.GetType("Demo.Program");

            // This call the static method Program.HelloWorld, passing two parameters to it.
            InvoqueMyMethod(myType, "HelloWorld", "Hello!", 123);

            // This call the static method Program.GoodbyeWorld, without parameters.
            InvoqueMyMethod(myType, "GoodbyeWorld", null);
        }

        static void InvoqueMyMethod(System.Type myType, string myMethodName, params object[] parameters)
        {
            myType.GetMethod(myMethodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, parameters);
        }

        static void HelloWorld(string text, int number)
        {
            Console.WriteLine("Hello World! - " + text + " - " + number.ToString());
        }

        static void GoodbyeWorld()
        {
            Console.WriteLine("Goodbye World!");
        }
    }
}

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question