TheDeveloperBlog.com


C# Anonymous Function Example

Anonymous functions. An anonymous function has no name. This kind of function offers more flexibility than a lambda expression. By using the delegate keyword, you can add multiple statements inside your anonymous function. It can use if-statements and loops.


Example. First, this example uses the FindAll method on the List type, which requires a delegate instance that receives one integer and returns a boolean. The argument to FindAll here demonstrates the anonymous method syntax.

And: We validate the argument using two if-statements. This cannot be done using a lambda expression.

Finally: A boolean expression is evaluated, causing the anonymous function to return true if the argument is greater than one.

C# program that uses anonymous method

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<int> values = new List<int>() { 1, 1, 1, 2, 3 };

	// This syntax enables you to embed multiple statements in an anonymous function.
	List<int> res = values.FindAll(delegate(int element)
	{
	    if (element > 10)
	    {
		throw new ArgumentException("element");
	    }
	    if (element == 8)
	    {
		throw new ArgumentException("element");
	    }
	    return element > 1;
	});

	// Display results.
	foreach (int val in res)
	{
	    Console.WriteLine(val);
	}
    }
}

Output

2
3

Lambda expressions. It is possible (even preferable) to use lambda expressions in this context. Usually, the simplest syntax form that fits your requirements is best. This is easiest to maintain and read.

Tip: To see examples of lambda expressions on the Find method, please visit the relevant article on this website.

List Find, FindAll

Specification. The best resource for the syntax of the C# language is the C# Specification. The annotated third edition presents section 7.14, which describes the syntax here in detail, with excellent comments by Don Box and Bill Wagner.

Tip: You can also find copies of the C# specification in PDFs on the Internet. But these may lack annotations.


Summary. There are several syntaxes available for higher-order functions in the C# language. Typically, the lambda expression syntax is clearest. But the syntax shown here can provide more powerful method bodies. It allows multiple statements.