I found two different ways to initialize a Delegate with an Action :
Create a new action or casting to Action.
Delegate foo = new Action(() => DoNothing(param));
Delegate bar = (Action)(() => DoNothing(param));
Is there a difference between this 2 syntaxes?
Which one is better and why?
Delegate is use in this example because the syntaxes is useful to call methods like BeginInvoke or Invoke with a lambda expression, and it's important to cast the lambda expression into an action
static main
{
Invoke((Action)(() => DoNothing())); // OK
Invoke(new Action(() => DoNothing())); // OK
Invoke(() => DoNothing()); // Doesn't compil
}
private static void Invoke(Delegate del) { }
But it's interesting to see that the compiler authorized this :
Action action = () => DoNothing();
Invoke(action);