Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Anonymous Method in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 932
    Comment on it

    Anonymous method is a method without any name and return type but have a body content and the optional arguments. This type of  method is created by using the delegate keyword. Return type of the anonymous method is dependence on the return statement written inside the method body. This anonymous method concept comes in C# 2.0 version.

     

    A sample program to illustrate how to use the anonymous method in c#

    delegate int delVar(int a, int b);
    
    class Program
    {
     delegate int del(int i, int j);
     static void Main(string[] args)
     {
     del d1 = delegate(int i, int j) { return i+j; };
     int result = d1(20,100 );
     Console.WriteLine(" Result = {0}",result);
     }
    }
    

     

    Output
    Result = 120

     

    Feature of an anonymous method:-

    1. Global variables can be accessed inside the anonymous method.
    2. A variable which are define inside the anonymous method will be local to that method only.i.e. other anonymous method have access scope for that variables.
    3. Anonymous methods doesn't retrieve the unmanaged code.
    4. Event handling have license to use an Anonymous methods.

     

    For example see the below code:

    <form id="form1" runat="server">
         <div>
        <h2>Anonymous Method Example For Event Handling</h2>
         <br />
         <asp:Label ID="lbl" runat="server" Font-Bold="true"></asp:Label>
         <br />
         <asp:Button ID="btnClick" runat="server" Text="Click Me" />  
         </div>
         </form> 
    
        
    

     

    protected void Page_Load(object sender, EventArgs e)
         {
         btnClick.Click += delegate { lbl.Text=" Click me for using an Anonymous method "; };
         }
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: