Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing definition for TryAdd() in Dictionary [closed]

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://learn.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)

like image 891
Ales100 Avatar asked Mar 25 '26 11:03

Ales100


1 Answers

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.

like image 135
V0ldek Avatar answered Mar 28 '26 01:03

V0ldek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!