2

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

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?

Vaaal88
  • 591
  • 1
  • 7
  • 25
  • 1
    Are these instance methods or static methods? You're describing them as if they were instance methods, but the example looks more like static methods. A [mcve] would really help here. – Jon Skeet Oct 18 '16 at 19:45
  • Unfortunately they are NOT static methods, and I cannot make them static methods. Maybe the example does not work, I didn't try it: I just pasted something found around here that seemed to create a list of function handle. – Vaaal88 Oct 18 '16 at 19:47
  • So please update your question to show them as instance methods, following the .NET naming conventions to be clear. – Jon Skeet Oct 18 '16 at 19:49
  • is this better? – Vaaal88 Oct 18 '16 at 19:57
  • 1
    Not really, in that it's still not a [mcve] as I requested before. But I suspect that SledgeHammer's answer is what you were after... that's why I was asking about whether or not they were instance methods to start with. It's worth bearing all this in mind for next time you ask a question - the clearer you are, ideally with an example, the quicker you're likely to get help. – Jon Skeet Oct 18 '16 at 19:59

1 Answers1

5

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:

lst[0](theInstance);
SledgeHammer
  • 7,338
  • 6
  • 41
  • 86