Search code examples
c#.netconcurrencyconcurrentdictionarytrygetvalue

Will my code ever be hit? ConcurrentDictionary TryGetValue(..)


If i have a concurrent dictionary, and i try a TryGetValue, and i test if that fails i do stuff, but if it doesn't fail, and the out value retrieved from the TryGetValuefunction is equal to what is was before i tried the TryGetValue, i do something else.

My Question is, (assuming nothing in my ConcurrentDicationary will ever be set to default(DateTime)), will my second if statement ever actually execute? or is it impossible given the current situation?

var m_unitsWaitingForReadResponse = new ConcurrentDictionary<string, DateTime>();
DateTime outVal = default(DateTime);
if (!m_unitsWaitingForReadResponse.TryGetValue("teststring", out outVal))
{
    //Do Stuff
}
if (outVal == default(DateTime))
{
    //Do Stuff 2
}

Solution

  • The MSDN documentation states that TryGetValue will return default(TValue) if the key doesn't exist in the dictionary. So yes, it should execute.

    You can test the return value of TryGetValue instead by simply using an else clause on the first if, like this:

    m_unitsWaitingForReadResponse= new ConcurrentDictionary<string, DateTime>();
    
    DateTime outVal = default(DateTime);
    
    if (!(m_unitsWaitingForReadResponse.TryGetValue("teststring", out outVal)))
    {
        //Do Stuff
    }
    else
    {
        //Do Stuff 2
    }
    

    I assume that your ConcurrentDictionary object will contain data at some point, using code not seen here.