Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use params in Action or Func delegates?

When I'm trying to use params in an Action delegate...

private Action<string, params object[]> WriteToLogCallBack;

I received this design time error:

Invalid token 'params' in class, struct, or interface member declaration

Any help!

like image 598
Homam Avatar asked Oct 30 '10 16:10

Homam


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.

When should I use params?

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 the difference between Func and Action delegate?

An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.

How do you use an Action delegate?

You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.


2 Answers

How about this workaround?

private Action<string, object[]> writeToLogCallBack;
public void WriteToLogCallBack(string s, params object[] args)
{
  if(writeToLogCallBack!=null)
    writeToLogCallBack(s,args);
}

Or you could define your own delegate type:

delegate void LogAction(string s, params object[] args);
like image 116
CodesInChaos Avatar answered Sep 28 '22 09:09

CodesInChaos


Variadic type parameters are not possible in C#.

That's why there're many declarations for Action<...>, Func<...>, and Tuple<...>, for example. It would be an interesting feature, though. C++0x has them.

like image 11
Jordão Avatar answered Sep 25 '22 09:09

Jordão