Jump to content

Func vs Expression

Posted on:May 2, 2017 at 02:00 AM

This is another post about C# basics :)

Our code sample is like following:

What we have here is Func ‘f’ and Expression ‘e1’ initialized with same value (x, y) => (x + y) * 2

Lines 21,22 and 23 will all print the same output: 6.

So what is the difference between Func and Expression?

At first it may seem strange why there are 2 similar concepts. It’s possible in initialize both Func and Expression with Lambda Expressions.

Func (and Action as well) is a delegate and Expression is binary tree

The screen below shows how Func<int, int, int>> look like. As you can notice method property is set. Func<int, int, int>> know what piece of code to run when it is executed. It does now know anything about the code structure inside assigned lambda expression.

Expression on the other side has Body and two sides:Left and Right. This structure is aware of assigned lamba expression structure. Every logical operation is represented by new node.

The last screen show left node from the parent structure. As you can see it contains its own Left and Right nodes populated with expressions.

Building Expressions manually

On the first screen (lines 14-19) you could spot that it is possible to build Expression Threes manually. This is very convenient way to create for example business rules in Business Rule Engines.

Serialization

Why you may want to serialize Func/Exception? On sample is when you want to query remote location. Good practice is to send filter over network. Such filter can be extended without altering interfaces with new parameters over and over again.

One thing worth mentioning is that only Expression can be serialized. Of course it depends strongly what you implement inside, but in general serialization is possible. Func, due to its nature (meaning the Method property) can not be serialized.