Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

629
Visualizações
Missing definition for TryAdd() in Dictionary

I am using example from tutorial https://www.dotnetperls.com/dictionary But I have problems with missing reference to TryAdd. Should I add some extra references for using this method? I did not find anything in documentation https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd?view=net-5.0

var items = new Dictionary<string, int>();
// Part 1: add the string with value 1.
bool result = items.TryAdd("test", 1);

Severity Code Description Project File Line Suppression State Error CS1061 'Dictionary<string, int>' does not contain a definition for 'TryAdd' and no accessible extension method 'TryAdd' accepting a first argument of type 'Dictionary<string, int>' could be found (are you missing a using directive or an assembly reference?) CsharpTest C:\path\to\file\Program.cs 672 Active

UPDATE: This method is for .NET 5 ang greater (I am using older framework)

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The comments are semi-right. This method was introduced in .NET Core 2.0 and .NET Standard 2.1, so you need your target framework to be at least that. In particular, it does not exist on .NET Framework (any version) and it does exist on the latest .NET 5.

If you need it in an older runtime, you can write up an extension method (taken from dotnet/runtime, System.Collections.Generic.CollectionExtensions).

public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    if (dictionary == null)
    {
        throw new ArgumentNullException(nameof(dictionary));
    }

    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, value);
        return true;
    }

    return false;
}

It has worse performance characteristics than the instance method of Dictionary<,>, since it does a separate lookup first, but it's unlikely to be relevant.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda