Advertisement
bero_0401

Delegates

Sep 29th, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | Source Code | 0 0
  1. using revision;
  2.  
  3. public class Program
  4. {
  5.     delegate int CalculateDelegate(int x, int y);
  6.  
  7.      
  8.     static void Main(String[] args){
  9.  
  10.         Calculate(10, 5, Add);
  11.  
  12.  
  13.         CalculateDelegate dlg = Substract;
  14.         Calculate(10, 5, dlg);
  15.  
  16.         CalculateDelegate dlg2 = new CalculateDelegate(Multiply);
  17.         Calculate(10, 5, dlg2);
  18.  
  19.  
  20.         Calculate(10, 5, delegate(int x , int y) { return x / y; });
  21.  
  22.         Calculate(10 , 5 , ( x , y ) =>  x % y); // lampda expression
  23.  
  24.  
  25.         // can call multiple functions
  26.  
  27.         dlg += Add;
  28.         dlg += Multiply;
  29.         dlg += Divide;
  30.         dlg -= Substract;
  31.  
  32.     }
  33.     static int Calculate(int x, int y , CalculateDelegate dlg) {
  34.         int result = dlg(x, y);
  35.         Console.WriteLine(result);
  36.         return result;
  37.  
  38.     }
  39.  
  40.     static int Add(int x, int y){
  41.         Console.WriteLine("Add");
  42.         return x + y;
  43.     }
  44.  
  45.     static int Substract(int  x, int y){
  46.         Console.WriteLine("Substract");
  47.         return x - y;
  48.     }
  49.  
  50.     static int Multiply(int x, int y) {
  51.         Console.WriteLine("Multiply");
  52.         return x * y;
  53.     }
  54.  
  55.     static int Divide(int x, int y) {
  56.         Console.WriteLine("Divide");
  57.         return x / y;
  58.     }
  59. }
  60.  
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement