Share via


Learning delegate, anonymous method, Action and Func

delegate

In C++, we have function pointers, so in C# we need a similar concept, which is "delegate". Delegate is a type, and type safe. We used it as the following 3 steps:

1) Declare a delegate type
Delegate void PrintDelegate(string message); // here PrintDelegate is a new delegate type

2) Construct a delegate
PrintDelegate print = new PrintDelegate(methodName); // by passing the real method

(3) Call this delegate
print("Hi");

anonymous method

This is easy! However, what if I don't have a methodName? "Anonymous method"! We can change above step 2) as follows

PrintDelegate print = delegate(string message)
                                  {
                                       Consonle.WriteLine(message);
                                  };
The anonymous method syntax is very similar with regular method syntax - parameter list, {} function body, but it does not have method name!

Action<T>
Ok, what if I don't want to declare a delegate type? Since a delegate is just a function pointer, can I use it directly? Yes, Action<T> can help. For above example, we can skip the first step and do the following 2 steps only

1)  Action<string> print = delegate(string message)
                                        {
                                            Consonle.WriteLine(message);
                                        };
// The parameter of Action's type is the parameter type of this method => in this case it is string

2) call this action
print("Hi");

Summary
(1)You will say, "yeah, Action is awesome!! We don't need to declare Delegate any more
(2)But, does action only can be used with "anonymous" method? No, you can use Action<message> print = methodName; // likes passing pointer
(3)However, it only support parameters, and does not support return values;
(4)From another perspective, it is a way to declare a method and pass it as a parameter, as we can pass Action<T>

e.g.void PassMethod(Action<int, string> print, int number, string message){ print(message, number); }

Func<T, TResult>

What if my method need a return value? Use Func<T, TResult>! It is very similar with Action, but its last parameter in this parameter list is the Return type.

        Func<string, int> print = delegate(string message)
                                              {
                                                    Consonle.WriteLine(message);
                                                     return 0; // the int type in the parameter list is the return type
                                               };