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


  • 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 …

gravatar Joseph Cooney Tuesday, July 6, 2010
Your comment re: javascript is bang on.

I like old-fashioned constructors, because intellisense makes finding out the parameters easy enough when writing the code, and F12 or mouse-over-tool-tip when reading is fine. I guess that's what I'm used to. Maybe in time I'll warm to the javascript-esque named arguments way in time.
Mike Wednesday, July 7, 2010
I believe the purpose of this VB styled ugliness is to make COM interop easier.. i.e. no more of this -

method("abc", null, null, null, null, null);

Understandable in this situation, but not a fan otherwise.
Michael g Wednesday, July 21, 2010
Not a fan. This is metadata, intellisense has the info - make the IDE smarter instead. Have an option to display *on screen* markup of the assignment.

Don't clutter my code repository (and the typing time) to regurgitate back what Intellisense already told me.

My 2 cents.
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!