Search code examples
c#generic-programming

Pass Action<.., .., T > as Parameter without a predefined number of action parameters


I have the following code:

public doSomething(List<Int64> data, Int64 counter){
    //Do something
}    

public doSomethingNext(List<Int64> data, String Something){
    //Do something next
}    

public static void Loop<T>(Action<T> action) {
        //Do something before
        action(T);
    }
}

Is it possible to write the Loop method in such a generic way, that I can pass every method regardless of the parameters of the method. Something like this:

Loop(doSomething,....?);
Loop(doSomethingNext,...?);

@Edit 19:40 24-06-2015 More information

Sorry the 'action(T);' part generates the error that T is unknown. However I filled it in there because I do not know how to make this work.

When I use the following code it works with Linq:

//Method
public static void Loop(Action action) {
    //Do something before
    action();
    }
}

//Call
Loop(() => doSomething(data, counter));

However I am curious if it can also work without Linq? (With something like < T >)

(A side-question, is it possible to be able to access the parameters of the method in the Loop function?)


Solution

  • Use a lambda method when calling Loop to transform your method into an Action:

     Loop(t => doSomething(t, counter));
    
     Loop(t => doSomethingNext(t, Something));