Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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")
    };
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!