Skip to content

Commit 877f769

Browse files
Copilotejsmith
andauthored
Fix InvalidCastException in InMemoryCacheClient.GetAsync<object>() for non-IConvertible types (#468)
* Initial plan * Fix InvalidCastException in GetValue<object>() for non-IConvertible types Co-authored-by: ejsmith <282584+ejsmith@users.noreply.github.com> * Extend test to cover CloneValues=true scenario Co-authored-by: ejsmith <282584+ejsmith@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: ejsmith <282584+ejsmith@users.noreply.github.com>
1 parent 6c6608c commit 877f769

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Foundatio/Caching/InMemoryCacheClient.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1767,7 +1767,7 @@ public T GetValue<T>()
17671767
object val = Value;
17681768
var t = typeof(T);
17691769

1770-
if (t == TypeHelper.BoolType || t == TypeHelper.StringType || t == TypeHelper.CharType || t == TypeHelper.DateTimeType || t == TypeHelper.ObjectType || t.IsNumeric())
1770+
if (t == TypeHelper.BoolType || t == TypeHelper.StringType || t == TypeHelper.CharType || t == TypeHelper.DateTimeType || t.IsNumeric())
17711771
return (T)Convert.ChangeType(val, t);
17721772

17731773
if (t == TypeHelper.NullableBoolType || t == TypeHelper.NullableCharType || t == TypeHelper.NullableDateTimeType || t.IsNullableNumeric())

tests/Foundatio.Tests/Caching/InMemoryCacheClientTests.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,6 +1596,25 @@ public async Task DoMaintenanceAsync_WithPositiveTimezoneOffset_ShouldNotThrowOn
15961596
Assert.Null(Log.LogEntries.SingleOrDefault(l => l.LogLevel == LogLevel.Error));
15971597
}
15981598
}
1599+
1600+
[Theory]
1601+
[InlineData(false)]
1602+
[InlineData(true)]
1603+
public async Task GetAsync_WithObjectType_ReturnsValueDirectly(bool cloneValues)
1604+
{
1605+
var cache = new InMemoryCacheClient(o => o.LoggerFactory(Log).CloneValues(cloneValues));
1606+
using (cache)
1607+
{
1608+
var data = new MyData("hello", 42);
1609+
await cache.SetAsync("key", data);
1610+
1611+
var result = await cache.GetAsync<object>("key");
1612+
Assert.True(result.HasValue);
1613+
Assert.Equal(data, result.Value);
1614+
}
1615+
}
1616+
1617+
private record MyData(string Name, int Value);
15991618
}
16001619

16011620
/// <summary>

0 commit comments

Comments
 (0)