Friday 24 June 2016

C# Tutorial - For Beginners & Professionals ~ C Sharp Anonymous Method

The concept of anonymous method was introduced in C# 2.0. 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. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.

A Simple Anonymous Method Example

  1. delegate int MathOp(int a, int b);
  2. class Program
  3. {
  4. //delegate for representing anonymous method
  5. delegate int del(int x, int y);
  6.  
  7. static void Main(string[] args)
  8. {
  9. //anonymous method using delegate keyword
  10. del d1 = delegate(int x, int y) { return x * y; };
  11.  
  12. int z1 = d1(2, 3);
  13. Console.WriteLine(z1);
  14. }
  15. }
  16. //output:
  17. 6

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.

Anonymous Method as an Event Handler

  1. <form id="form1" runat="server">
  2. <div align="center">
  3. <h2>Anonymous Method Example</h2>
  4. <br />
  5. <asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
  6. <br /><br />
  7. <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
  8. <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
  9. </div>
  10. </form>

  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. }
 
Summary
In this article I try to expose anonymous method with simple example. I hope after reading this article you will be able to use anonymous method in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

No comments:

Post a Comment