Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Anonymous Method in .NET

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 27
    Comment on it

    Anonymous methods are code just like delegates.They contain the body part without defining the signature associated. When writing an anonymous methods you need not specify the return type.

    These methods are declared with the creation of the delegate instance, with a delegate keyword for more see the example below:

    delegate void NumberChanger(int n);
    ...
    NumberChanger nc = delegate(int x)
    {
       Console.WriteLine("Anonymous Method: {0}", x);
    };
    

     

    The following code will give a better idea for implementing the anonymous method:

    using System;
    
    delegate void NumberChanger(int n);
    namespace DelegateAppl
    {
       class TestDelegate
       {
          static int num = 10;
          public static void AddNum(int p)
          {
             num += p;
             Console.WriteLine("Named Method: {0}", num);
          }
    
          public static void MultNum(int q)
          {
             num *= q;
             Console.WriteLine("Named Method: {0}", num);
          }
    
          public static int getNum()
          {
             return num;
          }
          static void Main(string[] args)
          {
             //create delegate instances using anonymous method
             NumberChanger nc = delegate(int x)
             {
                Console.WriteLine("Anonymous Method: {0}", x);
             };
    
             //calling the delegate using the anonymous method 
             nc(10);
    
             //instantiating the delegate using the named methods 
             nc =  new NumberChanger(AddNum);
    
             //calling the delegate using the named methods 
             nc(5);
    
             //instantiating the delegate using another named methods 
             nc =  new NumberChanger(MultNum);
    
             //calling the delegate using the named methods 
             nc(2);
             Console.ReadKey();
          }
       }
    }
    
    .net

 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: