I'm curious about the differences between calling a Func<T>
directly vs. using Invoke()
on it. Is there a difference? Is the first syntactical sugar and calls Invoke()
underneath anyway?
public T DoWork<T>(Func<T> method)
{
return (T)method.Invoke();
}
vs.
public T DoWork<T>(Func<T> method)
{
return (T)method();
}
Or am I on the wrong track entirely?
An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
The basic difference between Func and Action delegates is that while the former is used for delegates that return value, the latter can be used for those delegates in which you don't have any return value.
TResult. The type of the return value of the method that this delegate encapsulates. This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.
There's no difference at all. The second is just a shorthand for Invoke
, provided by the compiler. They compile to the same IL.
Invoke works well with new C# 6 null propagation operator, now you can do
T result = method?.Invoke();
instead of
T result = method != null ? method() : null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With