C# 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

Define an anonymous method with the delegate keyword


using System;//  w ww  . j a va  2s  .c om

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   w  ww  .  j  a  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;/* ww w  .j  a  v  a  2  s  .c o  m*/
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"));

    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Lambda Expressions
  2. How to create Lambda Expressions
  3. Example for Lambda Expressions
  4. Note for Lambda Expressions
  5. Lambda and Func and Action delegates
  6. Explicitly Specifying Lambda Parameter Types
Home »
  C# Tutorial »
    C# Types »
      C# Delegate
C# Delegate
C# Multicast Delegates
delegate parameters
C# Generic delegate
C# Func and Action
C# Anonymous delegate