a developer's notes – a semi-technical web development BLOG

March 31, 2013

Action and Func delegates in .NET extension methods

Filed under: C# — Duy Nguyen @ 7:11 pm
Tags: , , , , ,

The Action delegate never returns a value.

// no params
Action printEmptyLine = () => Console.WriteLine();

// one param
Action printNumber = x => Console.WriteLine(x);

// two params
Action<int, int> printTwoNumbers = (x, y) =>

A Func delegate returns some sort of value.

// at minimum, you have to specify the return type
Func getTime = () => DateTime.Now; // returns a type DateTime

// two params. The last param is the return type.
Func<int, int> square = x => x * x; // takes an int, returns an int

// three params
Func<int, int, int> multiple = (x, y) => x * y; // takes an int, returns an int

Using the delegates, you can just invoke them like this:

// using Action delegates
printTwoNumbers(5, 10);

//using Func delegates
DateTime now = getTime();

Now when you use extension methods, will understand what it needs.

For example:
So the above, you know the where method takes a Employee type and returns a bool.

A Linq Expression

//This is the same Func delegate but there is an Expression Type around it.
Expression<Func<int, int, int>> multipleExpression = (x, y) => x * y; // takes an int, returns an int

You can’t just invoke expressions. You’d have to turn them back into delegates to use. Like this:

Func<int, int, int>> multipleExpression = multipleExpression.Compile();

Expressions are mainly used for Linq to SQL. Func and Action delegates are used in Linq to Objects.

When using any extension method, if you see a parameter for a Func, Action, or Expression, they all accept lambda expressions.

Create a free website or blog at WordPress.com.