Rinne Rinne - 1 month ago 6
C# Question

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!

Answer

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();
}
Comments