C# Anonymous delegate
In this chapter you will learn:
- Define an anonymous method with the delegate keyword
- for loop in an anonymous delegate
- 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:
- What are C# Lambda Expressions
- How to create Lambda Expressions
- Example for Lambda Expressions
- Note for Lambda Expressions
- Lambda and Func and Action delegates
- Explicitly Specifying Lambda Parameter Types