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) =>
                 {
                     Console.WriteLine(x),
                     Console.WriteLine(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
printEmptyLine();
printNumber(3);
printTwoNumbers(5, 10);

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

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

For example:
whereFunc
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.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: