the ability to create a callback method is common. C# is a typed language, so in order to define typed callback (return and parameter types), you create a delegate. so the result of defining a delegate is new type of delegate.
delegate bool IsValid(string s); // define a new type of callback that
// returns bool and take a string parameter
...
IsValid callback; // define a variable of delegate type IsValid
callback = s => s?.Length > 1; // using lambda, define a callback function
var result = callback("test"); // invoke the callback code
delegates are so handy, that when when generic were added, were created generic delegates where created so the delegate type need not be predefined:
- Action<> a void delegate of parameter types
- Func<> a delegate of parameters types and a return type
- Predicate<> a delegate of parameters types and a return type of bool
Action<string> callback = s => Console.WriteLine(s);
callback("test");
Func<string,bool> isvalid = s => s.Length > 10;
bool result = isvalid("test");
Predicate<string> isvalid2 = s => s.Length > 10;
bool result2 = isvalid2("test");
an event is a collection of delegates. generally they are defined as void, as you can not access the return value;
delegate void StringHandler (string s); // define delegate
event StringHandler callbacks; // define event variable of type StringHandler
...
callbacks += s => Console.WriteLine(s); // add a callback
callbacks += s => Console.WriteLine(s); // add another
callbacks.Invoke("test"); // writes "test" twice to console