Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
3. Delegates and events: closure
//3. Delegates and events: closure using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { delegate bool TestPointer(int a); static event TestPointer SomeEvent; public static void Main(string[] args) { Subscribe(); // a that was local to Subscribe() is gone. //However when we fire event it is printed just fine. SomeEvent(0); //This is achieved by compiler which constructs special class that holds copy of all the variables that are referenced in the event handler. //This is called closure and allows us to use anything that was available at the time of subscription, no matter when it will actually be called. //If we use complex types than closure classes will keep references to them, so we can use them as well. } public static void Subscribe() { int a = 5; //a is local variable to this method and will be removed from memory as soon as this method is over SomeEvent += f => { Console.WriteLine("a is " + a); //we use a, when original a is not there anymore! return true; }; } } }
run
|
edit
|
history
|
help
0
Customised Code Dashboard
EnumToList
Date Diff
Events
15
LoL
newstring vs regex
Convert string to TimeSpan in C#
StudentUserInput
30272 Program Ex1