Boris Eetgerink

July 18, 2023

Using an options builder with Action<T>

When I started working on ConsoleExtensions, I made method overloads for every combination of parameter I found reasonable. However, that quickly got out of control. Now I'm ready to work on introducing an options builder so that eventually every feature gets one method that can be configured with an Action<T> delegate. Here's how that works for future reference.

Note optionsAction?.Invoke(options). It might happen that optionsAction is null. This makes sure no null reference exception is thrown and will use the default options in that case.

string input = ReadLine(options => {
    options.Prompt = ">";
    options.DefaultInput = "Hello, World!";

static string ReadLine(Action<ReadLineOptions> optionsAction)
    ReadLineOptions options = new();

    return options.DefaultInput;

class ReadLineOptions
    public string Prompt { get; set; } = string.Empty;
    public string DefaultInput { get; set; } = string.Empty;

About Boris Eetgerink

Hey, thanks for reading my blog. Subscribe below for future posts like this one and check my personal site in order to contact me.