C# expression trees

We want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).

With Lambda expressions we can write less code, and the code will be more readable.

A lambda expression uses the lambda operator => which means goes to.

arguments => expession

The expression reads: arguments goes to expression.

Let’s start with a common example;

using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine(Square(5));
            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }
    }
}

we declare a method called Square of type int with one input parameter of type int. It multiplies the number and returns the result.

In the Main() method we call our Square method with an int as a parameter.

We can convert this function into a Lambda expression. This is what it would look like:

num => num * num;

This expression would read: num goes to calculation (num * num).

This expression is short and easily readable once we get used to it. The catch though, is that a Lambda expression must be assigned to a delegate.

Resources

https://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct

https://tyrrrz.me/blog/expression-trees

https://thesharperdev.com/an-introduction-to-c-expression-trees/

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect