0

I have created a class library, which has 4 classes each class have 1 method. First class is the main class for me, in my first class, i have a string called calltoaction, in this string i will be getting the one of below list dynamically

  1. class2.Method2()
  2. class3.Method3()
  3. class4.Method4()

now i want to execute the "class2.method2" from the string "calltoaction".

Say for ex:

class Class1
{
    public void method1()
    {
        string calltoaction = "Class2.Method2()";
    }
}

How to execute the "Class2.Method" from the string?

Jey
  • 2,137
  • 4
  • 22
  • 40
  • 2
    Can you explain with a little more clarity? If you just want `method1()` to call `Class2.Method2()` then when not call it directly? – dtsg Jul 26 '12 at 14:59
  • 4
    Whilst this can be done, it generally shouldn't be done. Why are you trying to do this? There is much likely a better way. – KingCronus Jul 26 '12 at 15:00
  • 2
    What you are looking for is called `Reflection`. There are numerous tutorials on this subject already. Maybe you could read these first. – Peter Jul 26 '12 at 15:00
  • you will need to use reflection if you want to be able to call any method without predefining with a switch statement. you can then look for methods matching the name you pass in, then invoke it. – WraithNath Jul 26 '12 at 15:06
  • MethodInfo methodInfo = type.GetMethod(methodName); if you decide to use reflection...I will advice you to share why you want to do this so that a simpler approach can be worked out – NoviceProgrammer Jul 26 '12 at 15:10
  • I will be assigning different methods from different class in my string whihc is in my class. when the sting is assigned any class.method, i want to execute that immediately. say for ex: sting calltoaction = "class2.method2", i want to executet this immediately – Jey Jul 26 '12 at 15:16
  • 3
    that's a really weird request! there's still the possibility this to be just a fake scenario to demonstrate a concept. anyway c# relies on the object oriented paradigm and owns a concept called polymorphism. it means you have an interface that several classes may implement and the caller don't need to be coupled to the specific classes. someone among the answers suggested you also have the chance to use delegates. using Reflection that way it's called abuse. – Diego D Jul 26 '12 at 15:17
  • @DiegoDeVita Not that weird; I might have to resort to this as well as my (third-party) methods have differing signatures so delegating them isn't straightforward. – SteveCinq Oct 26 '20 at 04:48

3 Answers3

4

I'm not entirely sure what you are trying to accomplish, but I am sure it can be done in a better way. Basically, if I understand your question correctly, calling this function returns the name of a class and method that you wish to execute.

If that is the case, I would drop the whole "string" thing indefinitely and start looking at delegates.

Consider this:

public class Class2
{
    public static void Method2() { } 
} // eo class 2

public class Class3
{
    public static void Method3() { } 
} // eo class 3

public class Class4
{
    public static void Method4() { } 
} // eo class 4

Now we'd come to our main class

public class MainClass
{
    private delegate void MethodDelegate();
    private List<MethodDelegate> delegates_ = new List<MethodDelegate>();

    // ctor
    public MainClass()
    {
        delegates_.Add(Class2.Method2);
        delegates_.Add(Class3.Method3);
        delegates_.Add(Class4.Method4);
    }

    // Call a method
    public void Method1()
    {
        // decide what you want to call:
        delegates_[0].Invoke(); // "Class2.Method2"
    } // eo Method1
}  // eo class Main
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • I will get one method one time in the string, i want to execute that method immediately. Say for Ex: String calltoaction = "Class2.Method2" , once assigned the value to the string, i want to call that method immediately. – Jey Jul 26 '12 at 15:13
  • You may need to elaborate on what you want to do. Delegates can be returned, passed around and worked with like any other variable type. then one simply calls `Invoke()` to execute it. I still do not understand why you might need string representations. – Moo-Juice Jul 26 '12 at 15:15
  • You can just use `Func` and `Action` for your delegates 98% of the time; there is rarely a need to create your own these days. Doing this helps make the code cleaner. Also, rather than calling the `invoke` method you can just write `delegates_[0]();` (just put parenthesis with the parameters after the delegate variable). – Servy Jul 26 '12 at 15:28
  • @Servy, there are situations where `Func` and `Action` are not particularly desirable. Also, thanks for pointing it out - but `Invoke` is a personal preference as it makes it pretty clear what i'm doing. I know that I can just call it as you suggest, but it's a habit I have due to readability :) – Moo-Juice Jul 26 '12 at 15:32
  • 1
    @Moo-Juice As I said, `Func` and `Action` apply 98% of the time, not 100% of the time. This is one of those situations where `Action` alone is just fine. You only can't use them if you need ref/out parameters, to represent a generic method, and a few other such edge cases, but they are quite rare. Just because they don't work for every case doesn't mean you shouldn't use them ever. – Servy Jul 26 '12 at 15:37
1

I guess a low tech way would be to use a switch statement like so:

using System;

namespace ConsoleApplication24
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Which method would you like to run?");
            RunMyMethod(Console.ReadLine());
        }

        private static void RunMyMethod(string p)
        {
            switch (p)
            {
                case "MethodOne();":
                    MethodOne();
                    break;
                case "MethodTwo();":
                    MethodTwo();
                    break;
                case "MethodThree();":
                    MethodThree();
                    break;
            }
        }

        private static void MethodThree()
        {
            //Do Stuff
        }

        private static void MethodTwo()
        {
            //Do Stuff
        }

        private static void MethodOne()
        {
            //Do Stuff
        }
    }
}
JMK
  • 27,273
  • 52
  • 163
  • 280
1

Use an Action instead of a string (Assuming you don't need a return value. If you do - use Func):

This is for an idea of how to use it:

public Form1()
{
    InitializeComponent();

    Action<string> calltoaction;
    calltoaction = Doit;
    calltoaction("MyText1");
    calltoaction = Doit2;
    calltoaction("MyText2");
}

void Doit(string s)
{ Text = s; }

void Doit2(string s)
{ textBox1.Text = s; }
ispiro
  • 26,556
  • 38
  • 136
  • 291