Created
June 8, 2017 11:38
-
-
Save lokialice/065448997d947fcb66c29fd82d546144 to your computer and use it in GitHub Desktop.
delegate in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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