0

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)
        {

        }
user584018
  • 10,186
  • 15
  • 74
  • 160
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Maxim Jan 28 '22 at 03:10

1 Answers1

3

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).

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111