35

I can't get the following to compile:

var x = new Action(delegate void(){});

Can anyone point out what I'm doing wrong?

Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
maxp
  • 24,209
  • 39
  • 123
  • 201

2 Answers2

68

You don't specify a return type when using anonymous methods. This would work:

var x = new Action(delegate(){});

Some alternatives:

Action x = () => {}; // Assuming C# 3 or higher
Action x = delegate {};
Action x = delegate() {};
var x = (Action) (delegate{});
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    @maxp, you can also use syntax such as `Action x = delegate() {};` - both being same so use as per your likings! – VinayC Jan 27 '11 at 11:13
  • 2
    @leppie: I don't like it either, but it's the minimal change required to make the OP's code compile :) I'll offer some alternatives... – Jon Skeet Jan 27 '11 at 11:30
20

Why not lambda notation?

Action myAction= (Action)(()=>
{
});
Zotta
  • 2,513
  • 1
  • 21
  • 27