13

I have to do through Action like this:

Action action = () => { ..// };
object o = action;

any way to do this:

object o = () =>{};  //this doesn't compile
Benny
  • 8,547
  • 9
  • 60
  • 93

3 Answers3

11

What about:

object o = (Action) (() => { ... });

Though I don't really know why you'd want to store it as an object in the first place...

Dean Harding
  • 71,468
  • 13
  • 145
  • 180
  • I am implement a message queue for a thread, command can be put in the queue for execution. – Benny Mar 11 '10 at 03:38
  • Hi, I'm kind of new here. What's the etiquette when someone posts an identical answer while I'm writing one. Should I just delete it? It seems kinds of superfluous now. – Spike Mar 11 '10 at 03:40
  • @Benny - If you can, consider using a generic structure like `Queue` so that the lambda expressions don't have to be cast as objects. – Greg Mar 11 '10 at 03:40
  • @Greg, well, sometime, i maybe want to put other object in the queue. so not just action. – Benny Mar 11 '10 at 03:42
  • @Spike - I'd leave your answer in place. It probably got more upvotes because you explained that delegates are objects. – Greg Mar 11 '10 at 03:43
  • @Spike, you don't have to delete it. that's how you get upvote. :) – Benny Mar 11 '10 at 03:43
11

Weeeell, delegates are objects, but lambdas aren't.

This object o = (Action)(() => {}); will compile, but I don't know if it looks any better.

Spike
  • 2,016
  • 12
  • 27
6

Another option, not all that different:

object o = new Action(() => { });
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • Actually, I like this one better. I mentally imagine the other solution as a constructor anyway. Might as well make it explicit. – Spike Mar 19 '10 at 14:07