Skip to content

Commit 4b52b7b

Browse files
authored
Add type checking in contexts try get value (#1700)
1 parent cf8b57b commit 4b52b7b

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
- NOTE: This can affect grouping. You can keep the original behavior by setting the option `KeepAggregateException` to `true`.
1010
- Serialize stack frame addresses as strings. ([#1692](https://github.com/getsentry/sentry-dotnet/pull/1692))
1111
- Improve serialization perf and fix memory leak in `SentryEvent` ([#1693](https://github.com/getsentry/sentry-dotnet/pull/1693))
12+
- Add type checking in contexts TryGetValue ([#1700](https://github.com/getsentry/sentry-dotnet/pull/1700))
1213

1314
### Features
1415

src/Sentry/Internal/Extensions/CollectionsExtensions.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,16 @@ public static TValue GetOrCreate<TValue>(
1010
this ConcurrentDictionary<string, object> dictionary,
1111
string key)
1212
where TValue : class, new()
13-
=> (TValue)dictionary.GetOrAdd(key, _ => new TValue());
13+
{
14+
var value = dictionary.GetOrAdd(key, _ => new TValue());
15+
16+
if (value is TValue casted)
17+
{
18+
return casted;
19+
}
20+
21+
throw new($"Expected a type of {typeof(TValue)} to exist for the key '{key}'. Instead found a {value.GetType()}. The likely cause of this is that the value for '{key}' has been incorrectly set to an instance of a different type.");
22+
}
1423

1524
public static void TryCopyTo<TKey, TValue>(this IDictionary<TKey, TValue> from, IDictionary<TKey, TValue> to)
1625
where TKey : notnull
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
Type: Exception,
3+
Message: Expected a type of CollectionExtensionsTests+Value to exist for the key 'key'. Instead found a System.Int32. The likely cause of this is that the value for 'key' has been incorrectly set to an instance of a different type.
4+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using System.Collections.Concurrent;
2+
3+
[UsesVerify]
4+
public class CollectionExtensionsTests
5+
{
6+
[Fact]
7+
public Task GetOrCreate_invalid_type()
8+
{
9+
var dictionary = new ConcurrentDictionary<string, object> {["key"] = 1};
10+
return Throws(() => dictionary.GetOrCreate<Value>("key")).IgnoreStackTrack();
11+
}
12+
13+
class Value
14+
{
15+
}
16+
}

0 commit comments

Comments
 (0)