Skip to content

Commit f84ee0f

Browse files
authored
added null handling for DictionaryExtension method (#1036)
1 parent 8d23e56 commit f84ee0f

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

src/SimplCommerce.Infrastructure/Extensions/DictionaryExtensions.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ internal static bool TryGetValue<T>(this IDictionary<string, object> dictionary,
2424
return true;
2525
}
2626

27-
value = default(T);
27+
value = default;
2828
return false;
2929
}
3030

@@ -38,7 +38,9 @@ internal static bool TryGetValue<T>(this IDictionary<string, object> dictionary,
3838
/// <returns>Value if found, default if can not found.</returns>
3939
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
4040
{
41-
return dictionary.TryGetValue(key, out var obj) ? obj : default(TValue);
41+
if (dictionary != null)
42+
return dictionary.TryGetValue(key, out var obj) ? obj : default;
43+
return default;
4244
}
4345

4446
/// <summary>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System.Collections.Generic;
2+
using SimplCommerce.Infrastructure.Extensions;
3+
using Xunit;
4+
5+
namespace SimplCommerce.Infrastructure.Tests
6+
{
7+
public class DictionaryExtensionsTests
8+
{
9+
internal class MockClass
10+
{
11+
}
12+
13+
[Fact]
14+
public void GetOrDefaultShouldReturnDefaultWithNullDictionary()
15+
{
16+
Dictionary<string, MockClass> dict = null;
17+
MockClass result = dict.GetOrDefault("key");
18+
Assert.Null(result);
19+
}
20+
21+
[Fact]
22+
public void GetOrDefaultShouldReturnCorrectValue()
23+
{
24+
MockClass mockClass = new MockClass();
25+
Dictionary<string, MockClass> dict = new Dictionary<string, MockClass> { { "key", mockClass } };
26+
MockClass result = dict.GetOrDefault("key");
27+
Assert.NotNull(result);
28+
Assert.Equal(mockClass, result);
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)