The type arguments for method cannot be inferred from the usage. (c#, lambda)

StackOverflow https://stackoverflow.com/questions/21194025

  •  29-09-2022
  •  | 
  •  

سؤال

Firstly, I am a complete beginner to advanced level programming. All I have done are tutorials to C++ found on the web. I'm facing this problem at work. I have seen similar queries but nothing has helped me understand.

Please note: I am terrible at terminologies like method, object, interface, etc. So I might have made a mistake somewhere further. I'm slowly learning.

Code Block 1:

public static class DummyClassName
{
    public static T DummyTemplateFunc<T>(DummyInterfaceName aaa1, Func<T> action)
    {
        T DummyVal = action();
        // blah blah code
        // blah blah code

        return val;
    }
}

Code Block 2:

public class ClassName2 : blah1 , blah2, blah3
{
    public void Method1(string DummyString)
     {
         DummyClassName.DummyTemplateFunc(_aaa1, ()=>Function1(_arg1, arg2));
     }
}

I'll try to explain what's happening to the best of my ability. The second bit of code is used over and over in the program with different Functions (or methods?) in place of Function1. (These functions come from a C++ program linked with this one. I don't know how)

If these functions are of any return type EXCEPT void, the program runs fine.

If a void-return-type function is used, I get the error

"The type arguments for method '****.****.DummyClassName.DummyTemplateName<T>
(****.****.DummyInterfaceName, System.Func<T>)' cannot be inferred from the usage. 
Try specifying the type arguments explicitly.' 

From what I understand, this is because when a void function is passed it takes the place of T in the first block of code and tries returning 'val'. That's why an error is thrown.

Can somebody help me find a workaround to this? I don't mind defining a completely different class/method specifically to handle void functions. I know which functions are of return type void.

هل كانت مفيدة؟

المحلول

Create another overload, taking Action instead of Func<T>:

public static class DummyClassName
{
    public static void DummyTemplateFunc(DummyInterfaceName aaa1, Action action)
    {
        // you cannot assign result to variable, because it returns void
        action();

        // I also changed method to return void, so you can't return anything
        // return something;

        // ofc you can make it return something instead
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top