23

So i have 2 classes named A and B.

A has a method "public void Foo()".

B has several other methods.

What i need is a variable in class B, that will be assigned the Foo() method of class A. This variable should afterwards be "executed" (=> so it should execute the assigned method of class A).

How to do this?

svick
  • 236,525
  • 50
  • 385
  • 514
nr1
  • 777
  • 3
  • 12
  • 31

2 Answers2

60

It sounds like you want to use a delegate here.

Basically, you can add, in class "B":

class B
{
    public Action TheMethod { get; set; }
}

class A
{
    public static void Foo() { Console.WriteLine("Foo"); }
    public static void Bar() { Console.WriteLine("Bar"); }
}

You could then set:

B b = new B();

b.TheMethod = A.Foo; // Assign the delegate
b.TheMethod(); // Invoke the delegate...

b.TheMethod = A.Bar;
b.TheMethod(); // Invoke the delegate...

This would print out "Foo" then "Bar".

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    thx a lot this is working. i was missing the "Action" keyword :) – nr1 Sep 09 '11 at 20:46
  • 3
    @nr1: There are actually many options there - `Action` will allow you to use a method that doesn't return a value and takes no parameters. You can use `Func` if your methods all take an int and return a string, for example. – Reed Copsey Sep 09 '11 at 20:52
18

Reed gave you the right answer. It's also worth pointing out that you can use other delegate signatures besides Action.

There are generic versions like Action<T> (one arg), Action<T1, T2> (two args), etc... Also if your method has a return type, check out Func<T, TResult>.

Or of course you can define your own delegate type.

JohnD
  • 14,327
  • 4
  • 40
  • 53