Delegate Types
A delegate is simply a reference to a method. Delegates can be stored and passed around in a variable, and hence they must have a type definition:private delegate int FuncTwoInts(int one, int two);
The line above defines the type FuncTwoInts. The FuncTwoInts type is a reference to a method that takes two int parameters and returns a single int result.
Delegate expressions
The FuncTwoInts type can be used to declare variables like this:private static int Add(int one, int two) { return one + two; } private FuncTwoInts theFunc = Add;Or like this:
FuncTwoInts theFunc = delegate (int one, int two) { return one + two; };Or this:
FuncTwoInts theFunc = (one, two) => { return one + two; };Or even like this:
FuncTwoInts theFunc = (one, two) => one + two;
Lambda expressions
The last two delegate examples above (the ones utilizing the => operator) are called lambda expressions. Lambda expressions are just a more efficient way of defining a delegate. If the function defined by the lambda expression is more than a single line, then the { } are required, as is the return keyword.Built-in delegate types
There is a family of built-in delegate types that can be used to declare delegate variables without the need to define a custom type.Action
The types that represent a delegate without a return value (void return) are the Action types in the System namespace.private Action supFunction = () => Console.WriteLine("Sup?!");Here's an example of a delegate that takes three parameters of different types:
private Action<string, int, bool> printThreeValues = (s, i, b) => Console.WriteLine($"string: {s}, int: {i}, bool: {b}");
Func
The Func family of delegate types can return a value of any type you wish. For example: Func<TResult> for no params and TResult return type.private FuncFunc<T1, T2, TResult> for two parameters and TResult return type. Here is an example of a delegate declaration that takes two string parameters and returns an int:twoPlusThree = () => 2 + 3;
private Func<string, string, int> sumCharacters = (s1, s2) => s1.Length + s2.Length;
my thanks to this course:
https://www.codingame.com/playgrounds/345/c-linq-background-topics/review
0 comments:
Post a Comment