elena1234

Delegates, Anonymous method and Lambda in C#

Dec 9th, 2021 (edited)
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Delegates
  4. {
  5.     class Program
  6.     {
  7.         // delegate defines the signature (returns type and parameters);
  8.         public delegate int Manipulate(int a);
  9.  
  10.         static void Main(string[] args)
  11.         {
  12.             // Create a instance of the delegate
  13.             var normalMethodDelegate = new Manipulate(NormalMethod); // allows methods to be passed as parameter; references to another method
  14.             Console.WriteLine(normalMethodDelegate(4));
  15.  
  16.             var result = AnotherMethod(normalMethodDelegate, 4);  // Pass delegate as a parameter
  17.             Console.WriteLine(result);
  18.  
  19.             Manipulate anonymousMethod = delegate (int a) { return a * 2; }; // Anonymous Method is a delegate () { } and returns a delegate
  20.             var anonymousResult = anonymousMethod(4);
  21.  
  22.             //Lambda expressions are everything which have  =>  left and right value; They can return delegate or an Expression of the delegate;
  23.             Manipulate lambdaDelegate = (a) => { return a * 2; };
  24.             var lambdaResult = lambdaDelegate(5);
  25.         }
  26.  
  27.         public static int NormalMethod(int a)
  28.         {
  29.             return a * 2;
  30.         }
  31.  
  32.         public static int AnotherMethod(Manipulate method, int b)
  33.         {
  34.             return method(b);
  35.         }
  36.     }
  37. }
  38.  
Add Comment
Please, Sign In to add comment