Rinne
Rinne

Reputation: 1

A way to store a method in a variable?

Hello I am new to programming. Basically I need to store a method A from class A in variable A from class B inside a method from class B but I cannot seem to find a way.

To give an example: Class A

public void methodA()
{
*method*
}

Class B

Delegate variableA; //I believe using Delegate is wrong

public void methodB();
{
variableA = ClassA.methodA();
}

Then in Class B there would be another method that will utilize the variable with the stored method.

public void methodC();
{
variableA;
}

This isn't the exact code I have but this is basically the gist of it. Any help is appreciated :)

Edit: Thanks for the help everyone!

Upvotes: 0

Views: 3995

Answers (3)

olk
olk

Reputation: 199

Use reflection:

public class A
{
    public void MethodA()
    {
        Console.WriteLine("MethodA");
    }

    public static void StaticMethodA()
    {
        Console.WriteLine("StaticMethodA");
    }
}

public class B
{
    MethodInfo mv = typeof(A).GetMethod("MethodA");
    MethodInfo smv = typeof(A).GetMethod("StaticMethodA");

    public void CheckA(bool useStatic)
    {
        if (useStatic) smv.Invoke(null, null);
        else mv.Invoke(new A(), null);
    }
}

class MainClass
{
    [STAThread]
    public static void Main(string[] args)
    {
        var b = new B();
        b.CheckA(true);
        b.CheckA(false);
    }
}

See details in MSDN.

Upvotes: 0

Paviel Kraskoŭski
Paviel Kraskoŭski

Reputation: 1419

ClassA definition:

public class ClassA
{
    public void MethodA() 
    {
        Console.WriteLine("Hello World!");
    }
}

ClassB definition:

public class ClassB
{
    private Action VariableA { get; set; }

    public void MethodB(ClassA classA)
    {
        VariableA = classA.MethodA;
    }

    public void MethodC()
    {
        VariableA();
    }
}

Program definition:

static void Main(string[] args)
{
    ClassA classA = new ClassA();
    ClassB classB = new ClassB();
    classB.MethodB(classA);
    classB.MethodC();
    Console.ReadLine();
}

Upvotes: 1

Vincent
Vincent

Reputation: 882

Here is an example:

public class Test
   {
       private Action<int> hiddenMethod = new Action<int>((i) =>
       {
           Console.WriteLine(i);
       });

       public void PublicMethod(int i)
       {
           hiddenMethod(i);
       }
   }

And using it:

class Program
{
    static void Main(string[] args)
    {
        Test t = new Test();
        t.PublicMethod(21);
        Console.Read();
    }
}

Upvotes: 0

Related Questions