Created
March 30, 2016 21:25
-
-
Save asduser/09f915d21faaf0b10063ff1da6aaa3d9 to your computer and use it in GitHub Desktop.
How does delegate work? Explanation via C#. Example based on abstract user account in bank.
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
| using System; | |
| namespace MyApplication | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| // Create a new account instance with initial amount. | |
| Account acc = new Account(500); | |
| // Register delegate to obtain internal operation messages. | |
| acc.RegisterStatService(MessageHandler.Show); | |
| // Now amount equals 900. | |
| acc.Put(400); | |
| // Now amount equals 900. | |
| acc.Withdraw(700); | |
| // Now amount equals 200. | |
| acc.Withdraw(200); | |
| // Will be refused. | |
| acc.Withdraw(100); | |
| Console.Read(); | |
| } | |
| } | |
| /// <summary> | |
| /// Main class to work with user account in bank. | |
| /// </summary> | |
| public class Account | |
| { | |
| private int _sum; | |
| public Account(int sum = 200) | |
| { | |
| _sum = sum; | |
| } | |
| public delegate void AccountStats(string message); | |
| private AccountStats del; | |
| public void RegisterStatService(AccountStats _del) | |
| { | |
| del = _del; | |
| } | |
| public void Withdraw(int num) | |
| { | |
| if (num <= _sum) | |
| { | |
| del("Amount " + num + "$ was withdrawn."); | |
| _sum -= num; | |
| } | |
| else | |
| { | |
| del("An attempt to withdraw "+ num +" $ was refused. Reason: Insufficient funds."); | |
| } | |
| } | |
| public void Put(int num) | |
| { | |
| _sum += num; | |
| del("You have put " + num + "$ into your account."); | |
| } | |
| } | |
| /// <summary> | |
| /// A special class to manage messages. | |
| /// </summary> | |
| public static class MessageHandler | |
| { | |
| public static void Show(string message) | |
| { | |
| Console.WriteLine(message); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment