user875234
user875234

Reputation: 2517

Is there a way to supply any number of types in a generic method?

What I mean is I have a method like this:

public static void CrossThreadUpdate<T1, T2, T3>(this Form form, Action<T1, T2, T3> action, object[] parms)
{
    form.BeginInvoke(action, parms);
}

but I don't want to have to create the same function for <T1>, <T1, T2>, <T1, T2, T3>, <T1, T2, T3, T4>, etc. I'm imagining something similar to Foo(params string[] bar).

Upvotes: 0

Views: 242

Answers (1)

John Wu
John Wu

Reputation: 52240

I would just do it this way:

public static void CrossThreadUpdate(this Form form, Action action) 
{
    form.BeginInvoke(action);
}

And call it this way, using closed variables instead of trying to pass the parameters separately:

this.CrossThreadUpdate( () => someAction(param1, param2, param3) );

This has the additional advantage of being type-safe, whereas params object[] is not, and would also result in boxing for struct types.

Upvotes: 5

Related Questions