How do I fix 'compiler error - cannot convert from method group to System.Delegate'?
Asked Answered
A

2

22
 public MainWindow()
 {
    CommandManager.AddExecutedHandler(this, ExecuteHandler);
 }

 void ExecuteHandler(object sender, ExecutedRoutedEventArgs e)
 {
 }

Error 1 Argument 2: cannot convert from 'method group' to 'System.Delegate'

Amuse answered 19/3, 2010 at 18:56 Comment(3)
What if you want the method to accept different signature delegates?Corymb
@Corymb make it generic?Amuse
Reading your comment I realized I didn't phrase the question correctly. I meant "What if you want the method to accept arbitrary signature delegates". As in having an unknown signature delegate as argument. Generics would have worked if C# had supported variadics. Otherwise it's beyond my view.Corymb
L
19

I guess there are multiple ExecuteHandler with different signatures. Just cast your handler to the version you want to have:

CommandManager.AddExecuteHandler(this, (Action<object,ExecutedRoutedEventArgs>)ExecuteHandler);
Locris answered 19/3, 2010 at 18:58 Comment(1)
Got it - new the delegate type: CommandManager.AddExecutedHandler(this, new ExecutedRoutedEventHandler(ExecuteHandler)); Actually even that wasn't necessary, my original code now seems to work fine. I didn't actually have two method definitions. I think this was maybe just a bug in VS where the error message was caused from some temporary object files. Weirdness.Amuse
E
1

I got this error due to a completely different problem.

        var engine = new Ingest(GetOperationType, GetSqlConnection);

    private static SqlConnection GetSqlConnection(string instanceCode, string defaultDB)
        =>  new SqlConnection($"Server={InstanceMap[instanceCode]};Database={defaultDB};Trusted_Connection=True;");


    private static Type GetOperationType(string operationName)
        => Type.GetType(typeof(BaseOperation).Namespace + "." + operationName + ", ConditioningEngine.EnginePlugins");

Both params to 'new Ingest...' are different types of delegate. The GetOperationType param had no problem while GetSqlConnection got the 'cannot convert from method group' error.
After trying the casting trick mentioned in the other answers the error changed to System.Data.SqlClient not referenced. After fixing the reference problem I could get rid of the cast. That is, the error was false. The casting trick was useful in letting me see what the real error was but the cast itself wasn't necessary. It seems the true error could be almost anything.

Extensile answered 9/6, 2020 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.