Question

C# 6 added auto-property initializers and so we can do

private List<LinearLayout> layouts1 { get; } = new List<LinearLayout>();

Is this better or worse than

private readonly List<LinearLayout> layouts2 = new List<LinearLayout>();

(N.B. this is related to the 2011 question .NET Properties - Use Private Set or ReadOnly Property?, but that includes a public getter alongside a private setter. Here I only have a private getter.)

Was it helpful?

Solution

If you take a look here, you'll see that the following code:

class Example
{
   private List<LinearLayout> layouts1 { get; } = new List<LinearLayout>();
}

Is lowered by the compiler to:

internal class Example
{
    private readonly List<LinearLayout> <layouts1>k__BackingField = new List<LinearLayout>();

    private List<LinearLayout> layouts1
    {
        get
        {
            return <layouts1>k__BackingField;
        }
    }
}

and the property gets further lowered to a get_layouts1() method.

In other words, auto-property initializers are pure syntactic sugar. They provide a means of using auto-properties, whilst still allowing the backing field to be initialised.

So from a mutability point of view, there's no difference between them at all. Both provide read-only access to a list that is initialised when an instance of the class is created.

It's possible that it creates a slight performance overhead as the method must be called to obtain the list reference, but it's likely that the CLR JIT optimises the method away and just accesses the field directly.

The most obvious use for private properties is for lazy loading/deferred execution purposes. There are other uses, but as a guideline, they are often pointless "noise". I'd not go so far as to say that using a private property is worse than just using a field, but I'd advise just using a read-only field for most cases.

OTHER TIPS

In this case they would function almost identically. There is one subtlety that would make the private property less than ideal:

  • The bytecode would access the List<LinearLayout> through a getter function. However, as soon as the bytecode is recompiled for your environment (which C# has done for a long time), the getter function would be optimized out, so not a real problem.

If they are used identically, there won't be any practical difference.

Licensed under: CC-BY-SA with attribution
scroll top