Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use the params keyword in a delegate?

Tags:

c#

.net

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?

like image 964
sl. Avatar asked Jul 16 '09 09:07

sl.


People also ask

How do you pass parameters to delegates?

You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

What is use of params keyword?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

What is delegate keyword?

The code that the compiler generates when you use the delegate keyword will map to method calls that invoke members of the Delegate and MulticastDelegate classes. You define a delegate type using syntax that is similar to defining a method signature. You just add the delegate keyword to the definition.

What does params mean in C#?

The "params" keyword in C# allows a method to accept a variable number of arguments. C# params works as an array of objects. By using params keyword in a method argument definition, we can pass a number of arguments.


1 Answers

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

like image 51
Jon Skeet Avatar answered Sep 28 '22 05:09

Jon Skeet