OdeToCode IC Logo

What’s Wrong With This Code? (#26)

Monday, January 24, 2011

A measurement consists of a high reading and a low reading, but the high and low values are optional. We also need to add measurements together, so the following C# code:

var m1 = new Measurement(lowValue: 3, highValue: 5);
var m2 = new Measurement(null, 3);
var m3 = new Measurement(6, 2);
Console.WriteLine(m1 + m2 + m3);

… should produce a total measure showing a low value of 9, a high value of 10 (effectively ignoring null values).

Unfortunately, something is wrong with the implementation...

public struct Measurement
{
    public Measurement(int? lowValue, int? highValue)
    {
        _lowValue = lowValue;
        _highValue = highValue;
    }

    public static Measurement operator +(Measurement first, 
                                         Measurement second)
    {
        var result = new Measurement
        {
            _lowValue = first._lowValue + second._lowValue,
            _highValue = first._highValue + second._highValue
        };
        return result;
    }

    public override string ToString()
    {
        return String.Format("{0}-{1}", _lowValue, _highValue);
    }

    private int? _lowValue;
    private int? _highValue;
}

Did you spot it?