How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
This article explains delegates, lambda expressions, extension methods and events in C#, and uses them for paging, filtering and enrollment notifications in the student application.
How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
In the previous article, we wrote the lines like students.Where(s => s.IsActive) without much explanation, and most of us use them every day. But when we don’t understand what is behind these lines, we copy them without knowing why they work, and we can’t fix them when they fail. These C# features also decide how much code we write. Without them, a simple filter needs a separate named method, and a notification to many listeners needs a hard-coded call to each of them. In this article, we are going to see the delegates, lambda expressions, extension methods and events, and how we use them in the Student Management System to reduce the code.
Student Management System series:
- How to structure an ASP.NET MVC application? - Part 1
- How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
- How does routing work, with custom, nested and area routes? - Part 3
- How to model the data with Entity Framework and LINQ? - Part 4
- How lambda expressions, extension methods, delegates and events reduce the code? - Part 5 (this article)
- How to build CRUD with Razor views and dependency injection? - Part 6
- How to remove the repeated code with a base controller, base service and base repository? - Part 7
- How to build the views with layouts, partial views and HTML helpers? - Part 8
- How to use filters, model binding and validation? - Part 9
- How to add registration, login, forgot password, change password, profile and logout? - Part 10
- How to build a Web API with ASP.NET MVC 4? - Part 11
- How to test the application and keep it clean? - Part 12
TL;DR Summary
- Delegate - A type which holds a reference to a method. It lets us pass the behavior as a parameter.
Func<>andAction<>- The ready-made delegate types, so we rarely need to declare our own.- Lambda expression - A short way to write the method body inline, with the
=>operator. - Extension method - A static method which looks like an instance method of an existing type, to add the functionality without changing or inheriting the type.
- Event - A delegate with the restriction that only the owner can raise it, outsiders can only subscribe or unsubscribe.
- Together they remove the repeated code and decouple the publisher from the subscribers.
Common Challenges
One method for every variation
Without the delegates, a method to find the active students, another to find the students of one department and another for the students above some age are three methods which differ in only one condition. The code is repeated, and every new condition is a new method.
The same helper code everywhere
The paging code, Skip and Take with the arithmetic, is copied to each list page. A mistake in one copy is a bug in one page only, which is the hardest kind to find.
The publisher knows all the listeners
When a student is enrolled, we send an email, write an audit record and update a waiting list. If the Enroll method calls all three directly, it knows about every one of them, and a new listener means a change in the enroll code. It breaks the Open Closed Principle.
Delegates
A delegate is a type-safe reference to a method. It is like a variable which holds a method, with the signature checked by the compiler. We can pass it as a parameter, store it and call it later.
public delegate bool StudentFilter(Student student);
public static List<Student> Find(List<Student> students, StudentFilter filter)
{
var result = new List<Student>();
foreach (var student in students)
if (filter(student))
result.Add(student);
return result;
}
Now one method serves any condition. The caller decides the condition. The .NET framework already gives the generic delegates, so we don’t declare our own most of the time,
Func<T, TResult>- A method which takesTand returnsTResult.Func<Student, bool>is exactly ourStudentFilter.Action<T>- A method which takesTand returns nothing.Predicate<T>- The same asFunc<T, bool>, used by some older APIs likeList<T>.FindAll.
Lambda expressions
A lambda expression is the short way to write the method for a delegate. In C# 2 we had the anonymous methods, and in C# 3 the lambda made them much shorter. Compare the three ways to give the filter,
// 1. a named method
private static bool IsActive(Student s) { return s.IsActive; }
var a = Find(students, IsActive);
// 2. an anonymous method (C# 2)
var b = Find(students, delegate(Student s) { return s.IsActive; });
// 3. a lambda expression (C# 3)
var c = Find(students, s => s.IsActive);
The same filter in the three forms reduces from four lines to one. The left side of => is the parameters, the right side is the body. When the body is a single expression, the result is returned automatically. For more statements, use the braces, s => { ...; return x; }.
A lambda can also use the variables of the method where it is written, which is called as a closure,
int minimumAge = 18;
var adults = students.Where(s => s.DateOfBirth <= DateTime.Today.AddYears(-minimumAge)).ToList();
Must Be Aware: The closure captures the variable and not its value at that time. If you change
minimumAgebefore the query is executed (remember the deferred execution of Part 4), the query uses the new value.
Func or Expression of Func
In Part 4, we saw that EF can translate s => s.LastName.StartsWith("Kum") to SQL. The difference is the type it is converted to. When the lambda is given to IEnumerable<T>.Where(Func<T, bool>), it is compiled to the code and runs in the memory. When it is given to IQueryable<T>.Where(Expression<Func<T, bool>>), it is kept as an expression tree which the provider can translate. The lambda looks the same, but the behavior is very different. It is the reason to keep the query as IQueryable until we finish adding the conditions.
Extension methods
An extension method adds a method to an existing type without changing the type or inheriting from it. It is a static method in a static class, and the first parameter has the this keyword. Let us write the paging code once, and use it in every list,
public static class QueryableExtensions
{
public static IQueryable<T> Page<T>(this IQueryable<T> query, int pageNumber, int pageSize)
{
return query.Skip((pageNumber - 1) * pageSize).Take(pageSize);
}
}
// the usage
var page = context.Students.OrderBy(s => s.LastName).Page(pageNumber, 10).ToList();
This is the second page of the student list, which is built with the Page extension method (five students per page, so the second page shows the next five),

Another example, a small helper on the Student for the display name,
public static class StudentExtensions
{
public static string FullName(this Student student)
{
return student.FirstName + " " + student.LastName;
}
}
Most of the LINQ itself is the extension methods on IEnumerable<T> and IQueryable<T>, defined in the System.Linq namespace. To use an extension method, the namespace of its class must be imported with using.
Must Consider: An extension method is only a syntax sugar for a static method, it can’t access the private members, and it can’t override a method of the type. Don’t use it to hide the business rules which belong inside the entity, for example
student.Enroll(course)should be a real method of the Student (Tell, Don’t Ask). Use the extensions for the helpers like paging, formatting and the conversions.
Events
An event is a delegate which gives a restriction, only the class which owns the event can raise it, and the others can only subscribe (+=) or unsubscribe (-=). It is the publisher and subscriber pattern built into the language.
The following diagram depicts our example, the enrollment notifications.

public class StudentEnrolledEventArgs : EventArgs
{
public int StudentId { get; set; }
public int CourseId { get; set; }
}
public class StudentService : BaseService, IStudentService
{
public event EventHandler<StudentEnrolledEventArgs> StudentEnrolled;
public void Enroll(int studentId, int courseId)
{
Execute("Enroll", () =>
{
var student = _students.Find(studentId);
if (student == null)
throw new NotFoundException("Student", studentId);
if (student.Enrollments.Any(e => e.CourseId == courseId))
throw new BusinessRuleException("The student is already enrolled in this course");
student.Enrollments.Add(new Enrollment { CourseId = courseId, CreatedOn = DateTime.UtcNow });
_unitOfWork.Commit();
});
OnStudentEnrolled(new StudentEnrolledEventArgs { StudentId = studentId, CourseId = courseId });
}
protected virtual void OnStudentEnrolled(StudentEnrolledEventArgs e)
{
var handler = StudentEnrolled;
if (handler != null)
handler(this, e);
}
}
The EventHandler<T> is the standard delegate for the events, it takes the sender and the event data. We copy the event to a local variable (handler) before the null check, so that another thread can’t remove the last subscriber between the check and the call.
The subscribers are added at the start of the application, in one place,
studentService.StudentEnrolled += (sender, e) => emailNotifier.SendEnrollmentMail(e.StudentId, e.CourseId);
studentService.StudentEnrolled += (sender, e) => auditLogger.Log("Enrolled", e.StudentId);
studentService.StudentEnrolled += (sender, e) => waitlistUpdater.Update(e.CourseId);
Note: The sample code raises the event, and the unit test subscribes to it. The email, audit and waiting list listeners are the Should features of Part 1, so they are not built in the sample.
The StudentService doesn’t know about the email, audit or the waiting list. A fourth listener is a new line in the wiring code, and the service is not touched. It is the Open Closed Principle with the language support.
A unit test for the event does not need any real listener, a lambda is enough to check that the event is raised,
[Test]
public void Enroll_AddsTheEnrollmentAndRaisesTheEvent()
{
_repository.Students.Add(new Student { Id = 7, LastName = "Kumar" });
StudentEnrolledEventArgs raised = null;
_service.StudentEnrolled += (sender, e) => raised = e;
_service.Enroll(7, 3);
Assert.AreEqual(1, _repository.Students[0].Enrollments.Count);
Assert.IsNotNull(raised);
Assert.AreEqual(3, raised.CourseId);
}
Must Be Aware: An event holds a reference to its subscribers. A long living publisher with the short living subscribers keeps them alive in the memory until they unsubscribe, which is the common cause of the memory leaks. Also, the events in a web application are in-process and synchronous. If a handler is slow or throws, the
Enrollcall is slow or fails too. For the work which must survive a crash or take long time, like sending the emails, put the work in a queue and process it separately.
Wrap up
In this article, we have looked at the delegates, lambda expressions, extension methods and events, and how they reduce the repeated code in our application. I appreciate your time and efforts to read this article. In the next article, I will walk you through how to build the CRUD screens with the controllers, Razor views and the dependency injection.
Related Posts
How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
This article follows one ASP.NET MVC request from routing to the Razor view, and explains what changes between .NET 4.0 and 4.5, mainly the async actions.
How to build a Web API with ASP.NET MVC 4? - Part 11
This article builds an ASP.NET Web API for students on the same service, with routing, status codes, content negotiation, validation, dependency injection and a jQuery client.
How to build CRUD with Razor views and dependency injection? - Part 6
This article builds the student list, create, edit, details and delete screens with a service layer, view models, validation, Post-Redirect-Get and dependency injection with Unity.