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

627
Views
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 answers
Answer question

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 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!