简体   繁体   中英

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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Is a bit odd documented.

Properties noted with { get; }{ 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>(); } 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.

Following the link in the documentation you linked, we have read-only properties :

Starting with C# 6, you can use expression body definition to implement a read-only property. To do that, use the following syntax:

 PropertyType PropertyName => expression;

The following example defines a Location class whose read-only Name property is implemented as an expression body definition that returns the value of the private locationName field:

 public class Location { private string locationName; public Location(string name) { locationName = name; } public string Name => locationName; }

(Emphasis mine)

To rephrase it: when you access the Name property, the value held by locationName is returned. If the value of locationName changes, and you access Name again, you get the new value of locationName .

It's equivalent to:

public string Name
{
    get => locationName;
}

Or

public string Name
{
    get { return locationName; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM