Uses of Action delegate in C#
MSDN says:
This delegate is used by the
Array.ForEach method and the
List.ForEach method to perform an
action on each element of the array or
list.
Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.
What is the difference between Delegate & Action in C#
Action
is a Delegate
. It is defined like this:
public delegate void Action();
You could create your own delegate types similarly to how you would create abstract methods; you write the signature but no implementation. You then create instances of these delegates by taking the reference of a method.
class Program
{
public static void FooMethod()
{
Console.WriteLine("Called foo");
}
static void Main()
{
Action foo = FooMethod; // foo now references FooMethod()
foo(); // outputs "Called foo"
}
}
When to use Action Delegate instead of Predicate Delegate
Predicate delegate as the name says constitutes a Predicate which would match a condition/predicate and return bool
. Where as Action delegate as the signature says doesn't return anything (one way work).
List<string>.RemoveAll()
requires a predicate cause, what if you want to remove all element T
from list which matches a specific condition?
Action Delegate in C#
That code will be compiled to something more or less similar to this, I hope it becomes clear now:
[CompilerGenerated]
internal class Closure<T>
{
public string Result {get; private set;}
private readonly string _templatePath;
private readonly T _data;
public Closure(string templatePath, T data)
{
_templatePath = templatePath;
_data = data;
}
public void DelegateMethod()
{
Result = Razor.Run(_data, _templatePath);
}
}
public static string RenderTemplate<T>(string templatePath, T data)
{
Closure<T> closure = new Closure<T>(templatePath, data);
ExecuteRazorMethod(closure);
return closure.Result;
}
private static void ExecuteRazorMethod<T>(Closure<T> closure)
{
try
{
closure.DelegateMethod();
}
.
.
.//irrelevant code
.
}
When & why to use delegates?
I agree with everything that is said already, just trying to put some other words on it.
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class, "Please feel free to assign any method that matches this signature to the delegate and it will be called each time my delegate is called".
Typical use is of course events. All the OnEventX delegate to the methods the user defines.
Delegates are useful to offer to the user of your objects some ability to customize their behavior.
Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.
When to use Action Delegate instead of Predicate Delegate
Predicate delegate as the name says constitutes a Predicate which would match a condition/predicate and return bool
. Where as Action delegate as the signature says doesn't return anything (one way work).
List<string>.RemoveAll()
requires a predicate cause, what if you want to remove all element T
from list which matches a specific condition?
Events, Delegates vs ActionsT
Action<T>
is just an easy generic way to use delegates. It's equivalent to delegate MyDelegate(T arg)
It was added to save you some typing and it really saves the reader a LOT of hassle when trying to figure out what your delegate uses as parameters.
The event
keyword has special meaning. It prevents this delegate from being triggered outside of the class. See this excellent answer for a discussion of why event
is important and when you would use it (or not).
Delegates vs Action, Func in C#
None of the Func
or Action
types allow out
or ref
parameters, so you'll have to define your own delegates if you need to use those e.g.:
public delegate bool TryParse<T>(string s, out T value);
Related Topics
Rounding Up to 2 Decimal Places in C#
Why Are Some Members Missing When Trying to Print an Object by Serializing to JSON
Algorithm for Intersection of 2 Lines
Calling Async Methods from Non-Async Code
Step by Step Tutorial to Use Sap. Net Connector with VS 2008
C# Pass Lambda Expression as Method Parameter
Register Background Task in Silverlight 8.1 App
Improve Wpf Datagrid Performance
Create a .Txt File If Doesn't Exist, and If It Does Append a New Line
Using Bindingoperations.Enablecollectionsynchronization
Validating for Large Files Upon Upload
How to Compile a C# File with Roslyn Programmatically
Dependency Injection - New Instance Required in Several of a Classes Methods
How to Get the Development/Staging/Production Hosting Environment in Configureservices
Why Re-Initiate the Dbcontext When Using the Entity Framework
How to Fix Wpf Error: "Program Does Not Contain a Static 'Main' Method Suitable for an Entry Point"