Zev Spitz
Zev Spitz

Reputation: 15317

Target-typed new expressions and implicit arrays

I can write the following to initialize a List<KeyValuePair<string, string>> in a field initializer:

List<KeyValuePair<string, string>> lst = new() {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

leveraging target-typed new expressions for both the containing List<> and the individual KeyValuePair<> structs.

Is it possible to similarly initialize an array? Target-typed new expressions can't be used for the array itself, because an array has to be initialized.

But the following -- using implictly-typed arrays -- doesn't compile:

KeyValuePair<string, string>[] arr = new [] {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

with:

CS0826 No best type found for implicitly-typed array

Upvotes: 3

Views: 732

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

You can remove the new[] part:

using System.Collections.Generic;

KeyValuePair<string, string>[] arr =
{
    new("Key1", "Value1"),
    new("Key2", "Value2")
};

That's only valid as part of a variable declaration though, which allow an array_initializer as the initial value, without the need for an array_creation_expression. Variable declarations include fields, of course:

public class Test
{
    private readonly KeyValuePair<string, string>[] arr =
    {
        new("Key1", "Value1"),
        new("Key2", "Value2")
    };
}

Upvotes: 8

Related Questions