Anonymous delegate

In this chapter you will learn:

  1. Define an anonymous method with the delegate keyword
  2. for loop in an anonymous delegate
  3. Anonymous delegate with parameter

Anonymous method with the delegate

using System;//from java2  s .  co m

class MainClass
{
   delegate int FunctionToCall(int InParam);

   static void Main()
   {
      FunctionToCall del = delegate(int x){
                        return x + 20;
                     };
      Console.WriteLine("{0}", del(5));
      Console.WriteLine("{0}", del(6));
   }
}

The code above generates the following result.

for loop in an anonymous delegate

using System;  //from ja v  a  2s  . c o m
  
delegate void Do();  
  
class AnonMethDemo {  
 
  public static void Main() {   
     Do count = delegate {  
      for(int i=0; i <= 5; i++)  
        Console.WriteLine(i); 
    }; 
 
    count();  
  } 
}

The code above generates the following result.

Anonymous delegate with parameter

using System;/* j  a v  a2s. com*/
using System.Collections.Generic;
using System.Text;
class Program {
    delegate string delegateTest(string val);

    static void Main(string[] args) {
        string mid = ", middle part,";

        delegateTest d = delegate(string param) {
            param += mid;
            param += " and this was added to the string.";
            return param;
        };

        Console.WriteLine(d("Start of string"));

    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use delegate array
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables