Search code examples
c#optimization

Will the C# compiler optimize away the re-evaluation of expression-bodied members?


If I write the following for a class member definition:

public List<string> Names => new() {
    "Foo",
    "Bar",
    "Baz"
};

... my understanding is that the expression gets evaluated every time the member is accessed, so a new instance of List<string> will get created each time. Will the C# compiler optimize this away and create just one instance that gets accessed each time? If not, does using the following collection expression make any difference?

public List<string> Names => [
    "Foo",
    "Bar",
    "Baz"
];

And if not, how can I get this kind of class member giving me a list of values which doesn't result in a new class being initialized each time it's accessed?


Solution

  • You could do this:

    public List<string> Names { get; } = new() {
        "Foo",
        "Bar",
        "Baz"
    };
    

    ...or using a collection expression:

    public List<string> Names { get; } = [
        "Foo",
        "Bar",
        "Baz"
    ];
    

    This will create an automatic get-only property, assigning the value only once, when the class is instantiated.

    If this is in fact a static list, you might as well make it "static":

    private static readonly List<string> _names = [
        "Foo",
        "Bar",
        "Baz"
    ];
    
    public IReadOnlyList<string> Names => _names;
    

    I changed the public type to IReadOnlyList to avoid mutation. You might also consider using FrozenSet for this case.

    Pro tip: A great way to see what your code will actually do on a lower level is sharplab.io