Galin Iliev's blog

Software Architecture & Development

C# 2.0 Anonymous methods can accept arguments

Wow! I just came across the great artile on CodeProject about C# Anonymous methods and guess what I learned - Anonymous methods can accept arguments. I did not know about this feature and I think I am going to use it a lot.

As shown in the following example, an anonymous method can accept arguments of any type. You can also use the keywords ref and out to tune how arguments are passed to the method:

class Program {
delegate int DelegateType( int valTypeParam, string refTypeParam,
ref int refParam, out int outParam);
static DelegateType GetMethod() {
return delegate( int valTypeParam , string refTypeParam,
ref int refParam , out int outParam ) {
System.Console.WriteLine( "Hello valParam:{0} refTypeParam:{1}",
valTypeParam, refTypeParam);
refParam++;
outParam = 9;
return valTypeParam;
}; // End of the body of the anonymous method.
}
static void Main() {
DelegateType delegateInstance = GetMethod();
int refVar = 5;
int outVar;
int i = delegateInstance( 1, "one", ref refVar, out outVar );
int j = delegateInstance( 2, "two", ref refVar, out outVar );
System.Console.WriteLine( "i:{0} j:{1} refVar:{2} outVar:{3}",
i, j, refVar, outVar);
}
}

For more information see C#2 Anonymous Methods
 

Loading