C# Anonymous delegate
Anonymous method with the delegate
Define an anonymous method with the delegate keyword
using System;/* w w w. j av a 2 s . 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; /* w w w .j a va 2 s. 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;//from w w w . ja v a 2 s . c om
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.