Reputation: 2411
I am currently trying to create a generic call that takes in a value that needs to be returned by the function that is being passed in. It would appear to be a simple generic method, but I for the life of me cannot figure out why it isn't working.
What I am looking to do is pass a method onto this method, so that it can call and API and handle any errors that it comes across. I want to pass a gRPC call across to the method, wrap it in a try catch then invoke and catch any errors. I figured a generic would be the best way to accomplish this but it doesn't seem to be working. If someone has a recommendation to what will work better, I am all ears.
The generic call I came up with is super simple:
public T MakeCall<T>(Func<T> calling)
{
var res = calling.Invoke();
return res;
}
The calling code is as follows
static void Main(string[] args)
{
var caller = new Caller();
caller.MakeCall<int>(Add(1, 2));
Thread.Sleep(Timeout.Infinite);
}
public static int Add(int one, int two)
{
return one + two;
}
It is giving me an error that says,
"int is not assignable to parameter type System.Func"
Upvotes: 0
Views: 65
Reputation: 3422
Because Add()
returns int
whereas int
is not Func<T>
. You can use () => Add(1,2)
as a parameter.
So the solution would be
caller.MakeCall<int>(() => Add(1, 2));
Upvotes: 2
Reputation: 186668
Well,
MakeCall<int>(Add(1, 2))
means "execute Add(1, 2)
and then call MakeCall<int>
with the result (which is int
)". You should put a Func<int>
, not int
:
MakeCall<int>(() => Add(1, 2))
Here
() => Add(1, 2)
is a Func<int>
which takes nothing and returns Add(1, 2)
result
Upvotes: 4