c# - Implicitly convert method group to Delegate (for argument of Control.Invoke) -


i'm working on windows forms application, , contains custom controls methods can potentially called threads other ui thread. these methods therefore bit prevent exceptions:

public void dosomestuff() {     if (invokerequired)     {         invoke((action)dosomestuff);     }     else     {         // stuff.     } } 

the explicit cast of method group dosomestuff action caught attention, , i've been looking delegates , other related subjects more have before.

although i've seen related questions here, haven't been able find answer mine, is:

why method group dosomestuff require explicit casting action in case?

if remove cast, 2 errors:

error 102 argument 1: cannot convert 'method group' 'system.delegate'

error 101 best overloaded method match 'system.windows.forms.control.invoke(system.delegate, params object[])' has invalid arguments

the fact compiler apparently confused overload of invoke use seems pretty big hint, i'm still not sure why can't figure out. expect compiler deduce first overload of invoke, takes single delegate argument, 1 should used.

i expect because there no problem if code written this:

action = dosomestuff; invoke(a); 

the method group dosomestuff can implicitly converted action delegate type, , action derives (technically?) system.delegate, invoke can handle argument a without trouble. why can't implicit conversion done compiler when try pass dosomestuff argument directly? honest i'm not convinced own logic here, still not sure i'm missing.

the problem not compiler has trouble picking overload. "best match" overload 1 want has invalid arguments. c# language not define implicit conversion method group (dosomestuff) system.delegate.

you might compiler should pick 1 of action/func types , has been requested language feature. right not part of c#. (i don't know why; hope language request goes through.)

system.windows.forms.control.invoke created in .net 1.0. today, 1 use following signatures:

void invoke(action action); task invokeasync(action action); 

and work.

try make migration await , stops being concern.


Comments