How to write methods in C# which take lambdas as parameters

Jordan Lee
Nov 23, 2019 · 3 min read

If you’re new to C# or ASP.NET Core, you’ve probably used methods which take lambdas as a parameter, but might not be sure how to write such methods yourself.

For example, let’s take the Configure method from an ASP.NET Core application straight out of the box:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Notice how a lambda expression is passed as an argument in the UseEndpoints() method? How do you write a method like that?

Lambda Expressions vs Delegates

First let’s go through the difference between them.

Delegates — A delegate is a reference type variable that holds the reference to a method.

Lambda Expressions — Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don’t need to specify the type of the value that you input thus making it more flexible to use.

Any lambda expression can be converted to a delegate type. The delegate type to which a lambda expression can be converted is defined by the types of its parameters and return value.

If a lambda expression doesn’t return a value, it can be converted to one of the Action delegate types;

Otherwise, it can be converted to one of the Func delegate types.

For example, a lambda expression that has two parameters and returns no value can be converted to an Action<T1,T2> delegate.

A lambda expression that has one parameter and returns a value can be converted to a Func<T,TResult> delegate.

What this means is that when writing a method which takes a lambda expression as a parameter, we would specify the parameter as a matching delegate.

Code Example

In this example I’ll be doing the following:

  • Create a Model class
  • Create an extension method which generates random data.
    This method will take a lambda expression as a parameter, which defines how the random data is generated.
  • Create an extension method which changes (mutates) the properties of the Model.
    This method also takes a lambda expression as a parameter, which defines the way the properties of the Model are mutated.

This is how my solution looks like:

Dependencies

In this example, I am using Faker.Net to generate random data. If you’re following along, make sure to install the following package:

Install-Package Faker.Net

Create Model Class

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Create Extension Methods

public static class PersonExtensions
{
public static void GenerateRandomName(this Person person, Func<Person> action)
{
var randomPerson = action();
person.FirstName = randomPerson.FirstName;
person.LastName = randomPerson.LastName;
}
public static void Mutate(this Person person, Func<string, string> action)
{
person.FirstName = action(person.FirstName);
person.LastName = action(person.LastName);
}
}

Lambda Expression as a parameter

Now we’re ready to test this out.

Below is a console app which uses the extension methods defined above.

using Faker;
using System;
using Workspace.Extensions;
namespace Workspace
{
public class Program
{
private static void Main(string[] args)
{
var randomPerson = new Person();
randomPerson.GenerateRandomName(() =>
{
return new Person()
{
FirstName = Name.First(),
LastName = Name.Last()
};
});
Console.WriteLine($"{randomPerson.FirstName} {randomPerson.LastName}"); // Output: Rico Wiegand
randomPerson.Mutate(x => x.ToUpper());
Console.WriteLine($"{randomPerson.FirstName} {randomPerson.LastName}"); // Output: RICO WIEGAND
}
}
}

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Jordan Lee

Written by

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Jordan Lee

Written by

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store