Below code throwing argument null exception for token.ExpiresOn
since token is not in cache and null
. Is there way to check both in IF
clause - token not in cache plus token expires less than utc now?
if (!_cache.TryGetValue("KEY", out TokenClass token) && token.ExpiresOn < DateTimeOffset.UtcNow)
{
}
CodePudding user response:
You really want to check if the token is not in cache or if it's expired. So just use ||
:
if (!_cache.TryGetValue("KEY", out TokenClass token) || token.ExpiresOn < DateTimeOffset.UtcNow)
{
// presumably, get a new token
}
This work because ||
is short-circuiting: if the left-hand part evaluates to true
, the right hand part is not evaluated (that code doesn't run). And so, if your token is not in cache, no need to check if it's expired (which is good because then you'd throw).