Code & Sundry

Jon G Stødle

Two getter properties enter, one is explained... and so is the other one too

261 words, 2 minutes to read

With the introduction of C# 6 there are now two types of automatic getter only properties:

public List<string> OldAndFamiliar { get; } = new[] { "Old", "and", "familiar" }.ToList();

public List<string> NewHotness => new[] { "New", "hotness" }.ToList();

They might look very similar, and in this case they will also return the same result. Under the covers, though, they are different.

Automatic properties in C# are defined by using get; and/or set;:

public string AutoProperty { get; set; }

The compiler will automatically generate a backing field and a getter and setter. Something akin this:

private List<string> autoProperty;
public List<string> AutoProperty
    get { return autoProperty; }
    set { autoProperty = value; }

You might have written something like this a lot of times when programming in C#.

Considering how automatic properties are generated by the compiler, it's now easier to understand how the two different getter only properties work.

The OldAndFamiliar version will become something akin to this:

private List<string> oldAndFamiliar = new[] { "Old", "and", "familiar" }.ToList();
public List<string> OldAndFamiliar 
    get { return oldAndFamiliar ; }

While the NewHotness version will become something akin to this:

public List<string> NewHotness
    get { return new[] { "New", "hotness" }.ToList(); }

As you can see, OldAndFamiliar will only asign the List<string> once (to the backing field). NewHotness will return a new List<string> every time.

The NewHotness version acts like a method, but it looks like a property. These are more or less the same:

public List<string> NewHotness => new[] { "New", "hotness" }.ToList();
public List<string> GetNewHotness() => new[] { "New", "hotness" }.ToList();

When to use which, is up to you and your use case.

Happy coding!