Passing func<> as a parameter?

Foo(Test); // Compiles in unity

Foo(Test); // Compiles in visual studio but not in unity
      
public void Foo<T0>(Func<T0> method)
{  

}

int Test()
{
    return 0;
}

Hi, I’m trying to use delegate to pass methods as parameters. Some of the methods I want to pass have return types so I need to use Funcs<>. I’d like to be able to just pass the function through without explictly specifiying the types, like so:

Foo(Test);

However unity gives me the following error:

Foo<T0>(System.Func<T0>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

So I need to use instead

Foo<int>(Test);

This isn’t a massive issue but some of the functions have up to 9 pararameters. I’m writing the networking framework for BROFORCE, and I want the API to be a user friendly to everyone else on the team as possible. Is it possible to work around this so that I don’t need to explicitly state the parameter types every time?

Thanks for you time!

A Func requires two parameters, the type parameter that the method encapsulates, and the return type that the method encapsulates.

In the example you provided:

Foo(Test);

I would say it is not compiling in Unity because implicitly you are defining a void type for function Foo, however Test does return an int. I guess Visual Studio just ignores the return parameter, but Unity considers it an inconsistency.

I can’t think of a way of not having to define the parameters everytime, if you want to keep it as generic as possible. However, maybe you could think of a collection of common cases and explicitely define delegates for those cases:

public delegate int CommonCase1Handler(string, int);
public delegate int CommonCase2Handler(string, string);
// And so on...

Your teammates can use specific functions that take those delegates as parameters when they suit their needs, or use a totally generic function when no suitable delegate is provided.

Thanks for the concise response!

I guess I will just have to do that :confused:

I think I can probably still use generic parameters at least.

public delegate int CommonCase1Handler<T0, T1>(T0 arg0, T1 arg1);