C# – Benefits of Passing a Delegate to the Constructor

cconfiguration

When answering a question on Stack Overflow, the library appeared to have a weird way to specify configuration, through an Action passed to the constructor:

public Parser(Action<ParserSettings> configuration)
{
    if (configuration == null) throw new ArgumentNullException("configuration");
    this.settings = new ParserSettings();
    configuration(this.settings);
    this.settings.Consumed = true;
}

internal Parser(ParserSettings settings)
{
    this.settings = settings;
    this.settings.Consumed = true;
}

So to specify the settings you provide a Action<ParserSettings> that modifies the settings:

var parser = new Parser( s => { s.CaseSensitive = false; } );

I don't understand what this pattern accomplishes. What is the benefit of passing a delegate to the constructor instead of just having the client code create and pass the ParserSettings to the constructor?

Best Answer

Passing a delegate allows the caller instantiating the object to inject custom initialization behavior. Note the configuration(this.settings) call in the constructor code, which executes the behavior provided by the constructor delegate.

I can think of a number of reasons why this might be handy. One hypothetical example might be that of providing platform independence. This is a command line parser; if the parser can be called on Windows or Unix systems, passing a first-class function to the constructor allows the initialization to detect the platform, and adjust the parser settings based on which platform it is running on.

Further Reading
Open-Closed Principle
Inversion of Control