Skip to content

Commit

Permalink
added null handling for DictionaryExtension method (#1036)
Browse files Browse the repository at this point in the history
  • Loading branch information
AreebaKhalid committed Sep 4, 2023
1 parent 8d23e56 commit f84ee0f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal static bool TryGetValue<T>(this IDictionary<string, object> dictionary,
return true;
}

value = default(T);
value = default;
return false;
}

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

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Collections.Generic;
using SimplCommerce.Infrastructure.Extensions;
using Xunit;

namespace SimplCommerce.Infrastructure.Tests
{
public class DictionaryExtensionsTests
{
internal class MockClass
{
}

[Fact]
public void GetOrDefaultShouldReturnDefaultWithNullDictionary()
{
Dictionary<string, MockClass> dict = null;
MockClass result = dict.GetOrDefault("key");
Assert.Null(result);
}

[Fact]
public void GetOrDefaultShouldReturnCorrectValue()
{
MockClass mockClass = new MockClass();
Dictionary<string, MockClass> dict = new Dictionary<string, MockClass> { { "key", mockClass } };
MockClass result = dict.GetOrDefault("key");
Assert.NotNull(result);
Assert.Equal(mockClass, result);
}
}
}

0 comments on commit f84ee0f

Please sign in to comment.