0

I tried to do this:

public static EventHandler ToEventHandler(this Action callback)
{...}

for some syntactic sugar when I want to pass a simple method like void x() to a method that's typed for an EventHandler.

But when I try to call this like so:

SomeMethod(x.ToEventHandler());

I get a compiler error:

x() is a 'method', which is not valid in the given context  

Since methods are first class citizens in .NET, I can't see why this shouldn't be possible. Why doesn't it like this, and is there another way to accomplish what I'm trying to do?

Joshua Frank
  • 13,120
  • 11
  • 46
  • 95

1 Answers1

0

You can't do this, because x is a method, and compiler won't magically turn a method by its identifier into a delegate when using extension methods (I believe it should be able to do so indeed...).

What you need is this: SomeMethod(new Action(x).ToEventHandler());

In the other hand, an EventHandler has two input parameters while you expect to use an Action (parameterless delegate...). I suspect that you're trying to this:

EventHandler handler = (sender, e) => callback();

...and then, if you're going this route, it's fine.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206