Search code examples
c#propertiesfieldreferralsexpression-body

Expression-bodied members doesn't create new instances?


I'm curiuous why Expression-bodied properties doesn't create persisant objects.

public List<string> Pages { get; } = new List<string>();

Does create a persistant isntance of List<string>, just like always.

But

public List<string> Pages => new List<string>();

Somehow this does craete a new instance, but seems to be volatile.

Even when adding a new string to Pages won't add it.

There's no runtime- nor compile-time error, but I think there should be at least a warning. It took me quite a while to figure it out.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Is a bit odd documented.


Solution

  • Properties noted with { get; } have an internal field that stores the value. However, the second example which is expression-bodied, declares the creation of the list as the getter, which means it will be ran every time you access it, and every time it creates a new list.

    As noted in comments, it is the same as get { return new List<string>(); }, to explain it in a different way.

    To change this behavior, you need to have an internal field which would store the List instance and the expression-bodied member to return it.