diff options
author | Andre Polykanine A.K.A. Menelion ElensĂșlĂ« <andre@oire.org> | 2017-10-26 22:22:40 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-10-26 22:22:40 +0300 |
commit | 4a40fa210a4e96946c2c80e469b44bc0252caad3 (patch) | |
tree | 92fc12e14ef2f50124d2e34f1c06f51a34a1a818 /csharp.html.markdown | |
parent | 7620e7b4a3c856229b2a11c52701428eef5fe81d (diff) | |
parent | 95b5f9a4c4fa17b1d4854185a08e2a3434944de0 (diff) |
Merge pull request #2946 from ksami/ksami-csharp-delegates
[csharp/en] #2314 Add delegates and events to csharp/en
Diffstat (limited to 'csharp.html.markdown')
-rw-r--r-- | csharp.html.markdown | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/csharp.html.markdown b/csharp.html.markdown index c98a7da9..24ce803e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -640,6 +640,54 @@ on a new line! ""Wow!"", the masses cried"; } } + + // DELEGATES AND EVENTS + public class DelegateTest + { + public static int count = 0; + public static int Increment() + { + // increment count then return it + return ++count; + } + + // A delegate is a reference to a method + // To reference the Increment method, + // first declare a delegate with the same signature + // ie. takes no arguments and returns an int + public delegate int IncrementDelegate(); + + // An event can also be used to trigger delegates + // Create an event with the delegate type + public static event IncrementDelegate MyEvent; + + static void Main(string[] args) + { + // Refer to the Increment method by instantiating the delegate + // and passing the method itself in as an argument + IncrementDelegate inc = new IncrementDelegate(Increment); + Console.WriteLine(inc()); // => 1 + + // Delegates can be composed with the + operator + IncrementDelegate composedInc = inc; + composedInc += inc; + composedInc += inc; + + // composedInc will run Increment 3 times + Console.WriteLine(composedInc()); // => 4 + + + // Subscribe to the event with the delegate + MyEvent += new IncrementDelegate(Increment); + MyEvent += new IncrementDelegate(Increment); + + // Trigger the event + // ie. run all delegates subscribed to this event + Console.WriteLine(MyEvent()); // => 6 + } + } + + // Class Declaration Syntax: // <public/private/protected/internal> class <class name>{ // //data fields, constructors, functions all inside. |