C#: Delegates (Func & Actions),Events and Expressions

vishal gupta
3 min readApr 7, 2021

Delegates provide a late binding mechanism in .NET. Late Binding means that you create an algorithm where the caller also supplies at least one method that implements part of the algorithm.

What is an Event?

  1. Events are notifications.

What is a Delegate?

  1. A delegate is a specialized class often called a “Function Pointer”.

2. The glue/pipeline between an event and an event handler.

What is an Event Handler?

Event handler is responsible for receiving and processing data from a delegate

public void btnSubmit_Click(object sender, EventArgse) {

// Handling of button click occurs here

}

Delegates in .NET

The .NET framework provides several different delegates that provide flexible options:

Action<T> — Accepts a single parameter and returns no value

Func<T,TResult> — Accepts parameter and return a value of type TResult

Expressions

But now that we’re working against the Entity Framework. The IQueryable interface is significant. It’s very much like IEnumerable. It represents a data source, something that I can query.

But unlike IEnumerable where everything has to happen in memory, using things that we’ve looked at before, like writing a foreach loop and using a yield keyword, IQueryable does not have to execute code in memory. When I invoke a method against the IQueryable interface, there is an opportunity for a technology like the Entity Framework to take my code in a way that it can be inspected and then translated into SQL. And the whole trick here is this expression that wraps the func.

When the C# compiler encounters this expression, it turns this lambda expression into a method, something that I can invoke. It’s executable code that has been compiled and placed into my assembly.

But let’s see what happens if I wrap this Func with the expression type. Now C# compiler will give me data structure that represents the code. And it is then up to the Entity Framework to inspect that expression and translate it into SQL statements.

But I can compile that expression into executable code.

--

--