Skip to content

Instantly share code, notes, and snippets.

@lokialice
Created June 8, 2017 11:38
Show Gist options
  • Save lokialice/065448997d947fcb66c29fd82d546144 to your computer and use it in GitHub Desktop.
Save lokialice/065448997d947fcb66c29fd82d546144 to your computer and use it in GitHub Desktop.
delegate in c#
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment