OdeToCode IC Logo

Named Arguments versus Object Initializers

Tuesday, July 6, 2010

The object initializer syntax introduced in C# makes it easy to work with "configuration" type objects.

public class TemperatureSetting
{
    public float Value { get; set; }
    public float Variance { get; set; }
    public float Threshold { get; set; }
}
// ...

var settings = new TemperatureSetting
                   {
                       Value = 104f,
                       Variance = 0.6f,
                       Threshold  = 1.2f
                   };

The code is easy to read, but, it becomes a bit trickier if you want some additional features from the class.

  • Properties should be read-only

    and

  • Ensure every property gets set to a non-default value.

There are a few ways to solve the problem. One approach is to hide the property setters and provide a non-default constructor.

public class TemperatureSetting
{
    public TemperatureSetting(float value, float variance, float threshold)
    {
        //...
    }

    public float Value { get; private set; }
    public float Variance { get; private set; }
    public float Threshold { get; private set; }
}

However, this approach makes construction difficult to read, unless you define variables for each value to give them a name.

var settings = new TemperatureSetting(104f, 0.6f, 1.2f);

// or

var value = 104f;
var variance = 0.6f;
var threshhold = 1.2f;
var settings = new TemperatureSetting(value, variance, threshhold);

Fortunately, C# 4.0 gives us named arguments - it's the best of both worlds.

var settings = new TemperatureSetting(
        value: 104f, 
        variance: 0.6f, 
        threshold: 1.2f
    );

All this code needs is an extra { and } and we can put a .js extension on the file …