Write Less Code: C# Properties

I inherited the responsibility of maintaining an internal development tool implemented in C#. I recently added new classes to extend the tool’s functionality. Several of the new classes uses several properties, and I found myself writing code similar to the following:

class Shape
{
    private int _width;
    private int _height;
    private bool _isVisible;

    public int Width {
        get {
            return _width;
        }
    }

    public int Height {
        get {
            return _height;
        }
    }

    public bool IsVisible {
        get {
            return _isVisible;
        }
        set {
            _isVisible = value;
        }
    }

    /* ... more code, including fields,
              properties, and functions ... */
}

Implementation of properties as is done in the above source code can fill whole screens. I found a concise way to write the above code while browsing references, and I present it here:

class Shape
{
    public int Width { get; }
    public int Height { get; }
    public bool IsVisible { get; set; }

    /* ... more code, including fields,
              properties, and functions ... */
}

According to Microsoft’s C# Programming Guide1, with auto-implemented properties, “the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors.” Separate fields for auto-implemented properties are not used because of private, anonymous backing fields. Setting property values for auto-implemented properties without set accessors can be done by providing an initialization value when creating the auto-implemented property or by assigning a value to the auto-implemented property within the constructor. A reduction of lines is evident in the above source code.

Questions, comments, and responses are welcomed and appreciated.

Leave a Reply