Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Clarify CacheExtensions.TryGetValue<TItem> documentation for type mismatch behavior#11959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
Copilot wants to merge2 commits intomain
base:main
Choose a base branch
Loading
fromcopilot/fix-cache-extensions-behavior

Conversation

Copy link
Contributor

CopilotAI commentedOct 23, 2025
edited
Loading

Summary

Fixes the documentation ambiguity inCacheExtensions.TryGetValue<TItem> andCacheExtensions.Get<TItem> to clarify that these methods handle type mismatches by returningfalse/default(TItem), not just when keys are absent.

Problem

The existing documentation stated thatTryGetValue<TItem> returns "true if the key was found;false otherwise", which was ambiguous and misleading. In reality, the method returnsfalse in two distinct scenarios:

  1. When the key doesn't exist in the cache
  2. When the key exists but the stored value can't be cast toTItem

This caused confusion, especially for instrumented cache decorators that track hit/miss metrics:

IMemoryCachecache=newMemoryCache(newMemoryCacheOptions());cache.Set("key",(object)"string-value");// Non-generic sees "hit" (returns true because key exists)cache.TryGetValue("key",outobject?obj);// true// Generic extension sees "miss" (returns false due to type mismatch)cache.TryGetValue<int>("key",outvari);// false

Changes

TryGetValue<TItem> Method

  • Summary: Updated to explicitly mention casting toTItem
  • Returns: Changed to "true if the key was found and the stored value can be cast toTItem;false otherwise"
  • Parameter: Clarified thatvalue is set todefault(TItem) for both missing keys and type mismatches
  • Remarks: Added comprehensive guidance explaining:
    • The method returnsfalse for both missing keys and type mismatches
    • Users needing to distinguish these cases (e.g., for instrumentation) should use the non-genericIMemoryCache.TryGetValue method, which returnstrue if the key exists regardless of type

Get<TItem> Method

  • Summary: Updated to clarify it returns values only when "present and castable toTItem"
  • Returns: Added thatdefault(TItem) is returned for both missing keys and type mismatches

Resolution

Addresses #38969 by providing clear documentation that helps developers understand the type-checking behavior and guides them toward appropriate alternatives when they need to distinguish between "key not found" and "key found with incompatible type" scenarios.

Original prompt

This section details on the original issue you should resolve

<issue_title>CacheExtensions.TryGetValue documentation and behavior are ambiguous for type mismatches (key present with incompatible type returns false)</issue_title>
<issue_description>### Description

When using Microsoft.Extensions.Caching.Memory.IMemoryCache with the generic extension method:

IMemoryCachecache= ...;cache.Set("k",(object)"string-value");// Under the hood: IMemoryCache.TryGetValue("k", out object? obj) == true// But the generic extension below returns false because obj is not int.boolfound=cache.TryGetValue<int>("k",outvari);// found == false

This reveals two problems:

  1. Behavioral ambiguity for instrumentation / decorators
    A decorator that instrumentsIMemoryCache.TryGetValue(object, out object?) will observe a hit (returnstrue because the key exists), while the calling code usingCacheExtensions.TryGetValue<T> observes a miss (false due to type mismatch). This makes consistent hit/miss accounting impossible when consumers use the generic extension.

  2. Documentation mismatch
    The current docs forCacheExtensions.TryGetValue<T> say: “true if the key was found; false otherwise.” In the scenario above, the key is found but the method returnsfalse. The real behavior is closer to:

“Returnstrue if the key was found and the stored value is of typeTItem (otherwise returnsfalse and sets return value todefault).”

Reproduction Steps

usingMicrosoft.Extensions.Caching.Memory;varcache=newMemoryCache(newMemoryCacheOptions());// Store as object/stringcache.Set("key",(object)"abc");// 1) Non-generic call sees "found"varfoundObj=cache.TryGetValue("key",outobject?obj);// true// 2) Generic extension reports "not found" for incompatible typevarfoundInt=cache.TryGetValue<int>("key",outvari);// false// Instrumented decorators counting "hits" in IMemoryCache.TryGetValue(object, out object?)// will count the first as a hit, while callers using the generic extension see a miss.Console.WriteLine((foundObj,foundInt));// (True, False)

Expected behavior

Docs and API guidance should clarify that the generic overload only returns true when the value existsand is compatible withTItem.

Expected behavior

  • CacheExtensions.TryGetValue<T> documentation should explicitly state:

"Returns true if the key was found and the stored value can be cast toTItem. Returns false otherwise (including type mismatches)."

  • Guidance should explain implications for decorators/instrumented caches.
  • (Optional stretch) Consider an additional API if presence-vs-type disambiguation is needed, but a doc fix alone would resolve most confusion.

Actual behavior

  • Non-genericIMemoryCache.TryGetValue(object, out object?) returnstrue if the key is present.
  • GenericCacheExtensions.TryGetValue<T> returnsfalse if the type does not match, even when the key exists.
  • Documentation implies only the first behavior ("true if the key was found”'), without mention of the type check.

Regression?

No. This appears to be the behavior since the generic extension was introduced. The issue is a documentation mismatch and missing guidance rather than a runtime regression

Known Workarounds

  • Use the non-generic overload when consistent hit/miss metrics are required in decorators.
  • Or, after a generic call returns false, double-check with the non-generic overload if you need to distinguish "key present with wrong type" from "key absent" scenario.

Configuration

No response

Other information

No response</issue_description>

<agent_instructions>Please fix the documentation based on the feedback provided in the issue.</agent_instructions>

Comments on the Issue (you are@copilot in this section)

@jozkee@rjmurillo thank you for reporting this. Your workaround is correct, and the documentation should be clearer about the type check in the "found" logic.

Fixes#11958


✨ Let Copilot coding agentset things up for you — coding agent works faster and does higher quality work when set up for your repo.

Co-authored-by: jozkee <16040868+jozkee@users.noreply.github.com>
CopilotAI changed the title[WIP] Fix ambiguity in CacheExtensions.TryGetValue<T> behaviorClarify CacheExtensions.TryGetValue<TItem> documentation for type mismatch behaviorOct 23, 2025
CopilotAI requested a review fromjozkeeOctober 23, 2025 19:48
Copilot finished work on behalf ofjozkeeOctober 23, 2025 19:48
@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-extensions-caching

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

Reviewers

@gewarrengewarrengewarren approved these changes

@jozkeejozkeeAwaiting requested review from jozkee

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

CacheExtensions.TryGetValue<T> documentation and behavior are ambiguous for type mismatches (key present with incompatible type returns false)

3 participants

@gewarren@jozkee

[8]ページ先頭

©2009-2025 Movatter.jp