DEV Community

Jon Stødle
Jon Stødle

Posted on • Originally published at blog.jonstodle.com on

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

#c

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();
Enter fullscreen mode Exit fullscreen mode

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; }
Enter fullscreen mode Exit fullscreen mode

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; }
}
Enter fullscreen mode Exit fullscreen mode

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 ; }
}
Enter fullscreen mode Exit fullscreen mode

While the NewHotness version will become something akin to this:

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

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();
Enter fullscreen mode Exit fullscreen mode

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

Happy coding!

This post was originally published on blog.jonstodle.com

Top comments (0)