Action and Func Delegates

Earlier in .NET, we had to declare our own delegates definitions. This was cumbersome and more importantly not very intuitive. It took me a lot of time to understand the concepts of delegates. The newer versions of .NET frameworks come up with two handy delegates that are very easy to use -


  • Action Delegate
    • This delegate allows us to encapsulate a method that is not going to return anything, i.e its return type is void.
    • The numerous overloads provided range from 0 to 16 and they are all generic, meaning they can all have different types based on your needs.
    • Since it covers till 16 input arguments, I feel that it is good enough to cover most of the cases. If your function needs more than 16 inputs, its probably a good time to refactor the function.
  • Func Delegate
    • The difference between this delegate and Action delegate is that Func allows for return types.
    • It also provides numerous overloads similar to Action delegate. The last type defined is considered to be the return type. 
    • Similar to Action delegates, I think that this is good enough to cover most of the scenarios.
public class A03ActionAndFunc
    {
        internal static void Run()
        {
            Action<string, int> someMethod1;
            Action<string, int, double> someMethod2;
            Func<string, string> someMethod3;
            Func<string, int, string> someMethod4;

            // based on business logic, we can decide which actual method to call
            someMethod1 = Example1;
            someMethod2 = Example2;
            someMethod3 = Example3;
            someMethod4 = Example4;

            someMethod1("someMethod1", 5);
            someMethod2("someMethod2", 5, 5.6);

            Console.WriteLine(someMethod3("someMethod3"));
            Console.WriteLine(someMethod4("someMethod4", 5));
        }

        private static void Example1(string s, int i)
        {
            Console.WriteLine("Args: " + s + ", " + i);
        }

        private static void Example2(string s, int i, double d)
        {
            Console.WriteLine("Args: " + s + ", " + i + ", " + d);
        }

        private static string Example3(string s)
        {
            return s.ToUpper();
        }

        private static string Example4(string s, int i)
        {
            return s.ToUpper() + ", " + i;
        }
    }
In the above example - 
  • The definition of someMethod3 suggests that it will take 1 input of type string and it will output type string.
  • The definition of someMethod4 suggests that it will take 2 inputs. One of type string and the other of type int. The output type will be string.
The output looks like:

No comments: