Skip to content

Drop the unused new() constraint from GetOrCreate(key, defaultValue) - #140

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/getorcreate-default-constraint
Sep 28, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/getorcreate-default-constraint

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #139

What changed

The IDictionary and ConcurrentDictionary overloads of GetOrCreate(key, defaultValue) in Extensions/DictionaryExtensions.cs required TVal : new(), but they never construct a value. As a result, calls with a string, an interface, or any type without a parameterless constructor failed to compile with CS0310.

This PR removes new() from both overloads. notnull and the runtime null checks stay. The one-argument overloads keep new(), because they do construct the value. Relaxing a constraint is source-compatible for existing callers.

Tests

  • Four tests: a string value and an IList<int> value, on Dictionary and on ConcurrentDictionary. Each checks that the value is inserted when missing, and that the existing value is returned on a later call.
  • With the library change reverted, the test project fails to compile with CS0310, as the issue describes. With the change, dotnet test Extensions.Test passes 146/146.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LasidbyRZfyxgW8Z9wQu9M


Generated by Claude Code

The IDictionary and ConcurrentDictionary overloads that take a default
value insert the value the caller supplies and never construct one, but
still required a parameterless constructor. Calls with a string, an
interface or any type without one failed to compile with CS0310, which
are exactly the cases the one-argument overload cannot serve either.

Relaxing the constraint is source-compatible. The one-argument overloads
keep new(), since they construct the value.

Fixes #139

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LasidbyRZfyxgW8Z9wQu9M
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GetOrCreate(key, defaultValue) won't compile for string, interface or other non-new()-able value types (CS0310)

2 participants