0

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

user875234
  • 2,399
  • 7
  • 31
  • 49
  • 3
    No, you cannot do that. The number of parameters must be known at compile-time. –  Jan 16 '20 at 18:22
  • 1
    This feature is called "variadic generics" and it is quite rare. I believe TypeScript has done some work in this area, but C# certainly has not. – Eric Lippert Jan 16 '20 at 18:53

1 Answers1

5

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Not the answer I was looking for but it's actually a lot nicer. – user875234 Jan 16 '20 at 18:32
  • I actually use this pattern all the time with great success, and even provided it in another [recent answer](https://stackoverflow.com/a/59726278/2791540) – John Wu Jan 16 '20 at 18:48