Vaaal88 Vaaal88 - 11 months ago 49
C# Question

Get the handle of a function of a class that has no instantiation yet

I am fairly new to C#.

What I want to do may seem convoluted.
Let's start by saying that I want to take a handle of some functions in order to execute them later on. I know that I can achieve this in the following way:

List<Action> list = new List<Action>();
list.Add( () => instanceA.MethodX(paramM) );
list.Add( () => instanceA.MethodY(paramN, ...) );

for(Action a in list) {

However, what if the instanceA object does not exists yet, but I know it will exists when I call the corresponding function? MethodX and MethodY are on an external library that I am not supposed to modify.

-why: think about this situation: the class A has 100 Methods, each returning a different float depending on the class A state. However, depending on some other state, we may want to access only the first 5 methods, or only the first and the fourth method. The class state to which this method applies may change over time.
My idea was to have a big lists with all the 100 methods, then by using indexes corresponding to the method, create a sublist LL with only the appropriate methods (for example, [1,2,3,4,5], or [1,4]).
Then, once that the object A is created, I would run in turn all the different method in the sublist LL, somehow as they were called by the object A.

Any idea about how to achieve that?

Answer Source

You can use List<Action<YourClass>>, then add like:

lst.Add(x => x.Method1());
lst.Add(x => x.Method2());

Then when you want to execute the method you pass in the instance: