Search code examples
c#.netasp.net-core.net-4.8

What does "= []" mean in C# / .NET Core ? How convert to .NET 4.8?


I have this code in a class in .NET Core:

public IEnumerable<MyDoctor> items { get; set; } = [];

I don't understand the = [] part. What does it mean?

I have an error when I try to compile this in .NET 4.8. How can I convert this code in .NET 4.8 ?


Solution

  • It's new collection expression.

    It allows for syntax:

    int[] ints = [1, 2, 3, 42];
    

    which is much JS-like syntax, very conscise.

    The idea behind is to have beautiful syntax and also optimize - if you specify [] for example, it will use best underlying type, for example where possible, Array.Empty<T>() will be used for [].

    So in your case, you can substitute [] with Array.Empty<MyDoctor>()