Wednesday 14 August 2013

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.

Features of 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.

Assign an Anonymous Method to a Delegate

  1. delegate int MathOp(int a, int b);
  2. public static void Main() { //statements
  3. MathOp op = delegate(int a, int b) { return a + b; };
  4. int result = MathOp(13, 14);
  5. //statements
  6. }

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. }
 

No comments:

Post a Comment