The Real world example code that has been repeatedly requested, has already been provided in an earlier answer by "Console.WriteLine" user.
As far as to why it has been provided, from what I understood, Action is a way to save keeping on defining new delegates of your own. Since it is a predefined delegate of particular signature types, you save the hassle of creating different delegates for each intended purpose. You just use the predefined Action delegate to point to your methods and run them. Same is the case with Func delegates.
More of a convenience really, rather than actual new functionality. Helps keep your code short and understandable, with less hassle.
As far as your point-wise questions,
- What are the difference between them
No difference. Action is a predefined delegate, intended to save you the trouble of repeatedly defining new delegates.
- When to use a delegate or action
Typically, a delegate (and action) is used in places where you need to have table-driven functionality. i.e., maybe a dictionary of methods corresponding to some particular requirement. Note that using Action here makes it easy to change the final method called, to point to some other method dynamically (maybe based upon some settings selected by user?)
class Program
{
static void Main()
{
Dictionary<string, Action> dict = new Dictionary<string, Action>();
dict["loadFile"] = new Action(LoadFile);
dict["saveFile"] = new Action(SaveFile);
dict["loadFile"].Invoke();
dict["saveFile"].Invoke();
}
static void SaveFile()
{
Console.WriteLine("File saved!");
}
static void LoadFile()
{
Console.WriteLine("Loading File...");
}
}
Another typical usage is for callback methods. Example would be where you use a BubbleSort class, passing the comparator method as a delegate to the class, which would be used by the BubbleSort class to allow your code to define the comparison logic, while taking care of everything else. This can also be used from threads which you've started, and the thread calls the delegate when some intermediate actions need to be informed to your code.
You can refer this SO post to see a great example of the above.
https://stackoverflow.com/a/3794229/1336068
- When not to use a delegate or action
The only reason I can think of not using them when the situation demands it, is if your delegate is going to be called millions of times in a short duration. There is a slight overhead involved, and if this is causing an application lag, then you might have to find a better way to solve this using direct reference to your functions, instead of through a delegate.
- When they can be an over kill
When you use them gratuitously without any real need. Otherwise, in most situations, they can be an elegant way to solve the above scenarios.
Also, read this SO answer to see the distinctions between normal methods, delegates to get a better understanding of where to use delegates/action/func
https://stackoverflow.com/a/17380580/1336068