sl.
sl.

Reputation: 363

Can you use the params keyword in a delegate?

I'd like to define a delegate that takes a couple of dates, an unknown number of other parameters (using the params keyword), and that returns a list of objects:

Func<DateTime, DateTime, params int[], List<object>>

Visual Studio doesn't like the syntax which is making me think this isn't allowed. Can anyone tell me why?

Upvotes: 33

Views: 13351

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499800

You can't use params for any parameter other than the last one... that's part of what it's complaining about.

You also can't use params in a type argument. This isn't just for delegates, but in general. For example, you can't write:

List<params string[]> list = new List<params string[]>();

You can, however, declare a new delegate type, like this:

delegate void Foo(int x, params string[] y);

...

Foo foo = SomeMethod;
foo(10, "Hi", "There");

Note that the method group conversion will have to match a method which takes a string array - you couldn't declare SomeMethod as:

void SomeMethod(int x, string a, string b)

and expect the above to work, for example. It would have to be:

void SomeMethod(int x, string[] args)

(Or it could use params itself, of course.)

Upvotes: 54

Sam Harwell
Sam Harwell

Reputation: 99859

You can't have custom attributes on a generic type argument (the CLI doesn't permit it), and the C# compiler implements the params keyword by emitting the System.ParamArrayAttribute on the relevant method parameter.

This stops you from using it with the System.Func<...> generic delegates, but you can always create your own delegate type that does use params.

Upvotes: 26

Related Questions