Use Funcs only if you want results back
If you are trying to encapsulate a method that returns a value, Funcs are ideal. However, what if your method returns void? Func will not work (Funcs were designed to wrap methods with return values only). However, a similar construct, called Action does just this – encapsulate a method without a return value. See usage of these two delegates below:
// Use Func only if the method that you are encapsulating returns a value Func<int, string> myFunc = (x) => String.Format("The int is {0}", x); myFunc.Invoke(4); // No returned value? Use Action instead Action<string> voidReturnType = (x) => Console.WriteLine(x);
Leave a Reply