Pass anonymous delegate

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet passes an anonymous delegate to a method which executes it a specified number of times.

public delegate int ConsoleDelegate (int value);
	
public class Test
{
   void ExecuteDelegate (ConsoleDelegate cd, int iterations)
   {
      for (int i=1; i <= iterations; i++)
      {
         Console.WriteLine ( "Iteration {0}: {1}", i, cd(i) );
      }
   }
 
   public static void Main( )
   {
      Test test = new Test();
      test.ExecuteDelegate 
         (delegate (int arg) { return arg + arg; }, 5);
   } 		
}

Personal tools