Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda