ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods


You should have this already: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd?view=net-7.0 but this is not always available in all environments.


/// <summary> Purpose: Prevents exception "Item with Same Key has already been added". </summary>
public static void TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary,
                                        TKey key, TValue value)
    if (!dictionary.ContainsKey(key))
        dictionary.Add(key, value);


// where Scenario is a custom object
Dictionary<Type, PageDrawerItem> targetViewDict = new Dictionary<Type, PageDrawerItem>();
targetViewDict.TryAdd(typeof(Scenario), mainVM.GetView(PageKind.Scenarios));

Author: Eric Wood

Submitted on: 6 dec. 2022

Language: csharp

Type: Dictionary

Views: 2561