diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ef320d..baf4273 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Added a method for determining if a culture uses 24 hour format - Added math util method for modulus - Added TimeSpan extension methods for cycling hours and minutes without modifying the day + - Added a dictionary extension method for getting or adding a new value via func ### Changed - The Root Config path in Net Standard will now be the ICD.Connect folder in the current environments ProgramData directory diff --git a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs index 9397b4c..58bf7f8 100644 --- a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs +++ b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs @@ -147,14 +147,38 @@ namespace ICD.Common.Utils.Extensions if (extends == null) throw new ArgumentNullException("extends"); - // ReSharper disable once CompareNonConstrainedGenericWithNull +// ReSharper disable CompareNonConstrainedGenericWithNull if (key == null) +// ReSharper restore CompareNonConstrainedGenericWithNull + throw new ArgumentNullException("key"); + + return extends.GetOrAddNew(key, () => ReflectionUtils.CreateInstance()); + } + + /// + /// 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, Func valueFunc) + { + if (extends == null) + throw new ArgumentNullException("extends"); + +// ReSharper disable CompareNonConstrainedGenericWithNull + if (key == null) +// ReSharper restore CompareNonConstrainedGenericWithNull throw new ArgumentNullException("key"); TValue value; if (!extends.TryGetValue(key, out value)) { - value = ReflectionUtils.CreateInstance(); + value = valueFunc(); extends.Add(key, value); }