diff --git a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs index cc3f582..6db705a 100644 --- a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs +++ b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs @@ -112,7 +112,6 @@ namespace ICD.Common.Utils.Extensions /// /// /// - [CanBeNull] [PublicAPI] public static TValue GetOrAddDefault(this IDictionary extends, TKey key, TValue defaultValue) @@ -130,6 +129,35 @@ namespace ICD.Common.Utils.Extensions return value; } + /// + /// If the key is present in the dictionary return the value, otherwise add a new value to the dictionary and return it. + /// + /// + /// + /// + /// + /// + [PublicAPI] + public static TValue GetOrAddNew(this IDictionary extends, TKey key) + where TValue : new() + { + if (extends == null) + throw new ArgumentNullException("extends"); + + // ReSharper disable once CompareNonConstrainedGenericWithNull + if (key == null) + throw new ArgumentNullException("key"); + + TValue value; + if (!extends.TryGetValue(key, out value)) + { + value = ReflectionUtils.CreateInstance(); + extends.Add(key, value); + } + + return value; + } + /// /// Gets a key for the given value. ///