Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically assign method / Method as variable

Tags:

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?

like image 520
nr1 Avatar asked Sep 09 '11 20:09

nr1


People also ask

What are dynamic type variables?

A dynamic type variables are defined using the dynamic keyword. Example: dynamic Variable. dynamic MyDynamicVar = 1; The compiler compiles dynamic types into object types in most cases. However, the actual type of a dynamic type variable would be resolved at run-time.

What is dynamic method in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

Can you create a function in C# which can accept varying number of arguments?

params (C# Reference)By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.


1 Answers

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".

like image 63
Reed Copsey Avatar answered Sep 22 '22 01:09

Reed Copsey