Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<T>() vs Func<T>.Invoke()

Tags:

c#

func

invoke

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?

like image 827
tris Avatar asked Apr 30 '13 21:04

tris


People also ask

What is the difference between Func and Action delegate?

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.

What is the difference between func string string and delegate?

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.

What is TResult in C#?

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.

What is func used for in C#?

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.


2 Answers

There's no difference at all. The second is just a shorthand for Invoke, provided by the compiler. They compile to the same IL.

like image 64
Jon Skeet Avatar answered Oct 19 '22 18:10

Jon Skeet


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;
like image 26
sanjuro Avatar answered Oct 19 '22 20:10

sanjuro