Skip to content

Commit 35f8bcf

Browse files
Copilotejsmith
andcommitted
Fix InvalidCastException in GetValue<object>() for non-IConvertible types
Co-authored-by: ejsmith <282584+ejsmith@users.noreply.github.com>
1 parent 6429ac8 commit 35f8bcf

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,6 +1596,23 @@ public async Task DoMaintenanceAsync_WithPositiveTimezoneOffset_ShouldNotThrowOn
15961596
Assert.Null(Log.LogEntries.SingleOrDefault(l => l.LogLevel == LogLevel.Error));
15971597
}
15981598
}
1599+
1600+
[Fact]
1601+
public async Task GetAsync_WithObjectType_ReturnsValueDirectly()
1602+
{
1603+
var cache = new InMemoryCacheClient(o => o.LoggerFactory(Log));
1604+
using (cache)
1605+
{
1606+
var data = new MyData("hello", 42);
1607+
await cache.SetAsync("key", data);
1608+
1609+
var result = await cache.GetAsync<object>("key");
1610+
Assert.True(result.HasValue);
1611+
Assert.Equal(data, result.Value);
1612+
}
1613+
}
1614+
1615+
private record MyData(string Name, int Value);
15991616
}
16001617

16011618
/// <summary>

0 commit comments

Comments
 (0)