Tuesday, September 12, 2017

Anonymous Method

An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type.

  1. class Program
  2. {
  3. //delegate for representing anonymous method
  4. delegate int del(int x, int y);
  5. static void Main(string[] args)
  6. {
  7. //anonymous method using delegate keyword
  8. del d1 = delegate(int x, int y) { return x * y; };
  9. int z1 = d1(2, 3);
  10. Console.WriteLine(z1);
  11. }
  12. }
  13. //output:
  14. 6
  15. Anonymous Method as an Event Handler
    1. protected void Page_Load(object sender, EventArgs e)
    2. {
    3. // Click Event handler using Regular method
    4. btnCancel.Click += new EventHandler(ClickEvent);
    5. // Click Event handler using Anonymous method
    6. btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; };
    7. }
    8. protected void ClickEvent(object sender, EventArgs e)
    9. {
    10. lblmsg.Text="Cancel Button clicked using Regular method";
    11. }
    12. Key points about anonymous method
      1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.
      2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
      3. We use anonymous method in event handling.
      4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
      5. Unsafe code can’t be accessed within an anonymous method.
      6. An anonymous method can’t access the ref or out parameters of an outer scope.

No comments:

Post a Comment