.net, C# tip, Clean Code

C# tip – specifying Optional parameters and clean code

I’ve recently been writing an API, and on one of the method overloads I needed to include a couple of optional attributes.

I knew this was possible in C# 4.0, and found that the canonical way of implementing this is to use the pattern below.

private static string EditorFor<TModel, TSelectedValue>(
    this HtmlHelper htmlHelper,
    Expression<Func<TModel, TSelectedValue>> formFieldName,
    string optionLabel = null,
    object htmlAttributes = null)
{
    // ...
}

This pattern makes sense to me for assignation of a default value to the parameter, but less sense as a way to indicate the parameter is optional.

I guess that once you’re used to seeing the pattern you learn to recognize it, but it doesn’t really convey the intent of the API.

After a little digging, I found that this isn’t the only way to indicate an optional parameter, and – in my opinion – the [Optional] parameter attribute more clearly demonstrates how I (as the API author) intended the method to be used:

private static string EditorFor<TModel, TSelectedValue>(
    this HtmlHelper htmlHelper,
    Expression<Func<TModel, TSelectedValue>> formFieldName,
    [Optionalstring optionLabel,
    [Optionalobject htmlAttributes)
{
    // ...
}

You can read more on MSDN about optional arguments here and the OptionalAttribute class here.