# ConcurrentDictionary methods

I am new to concurrent dictionaries and all their new methods involving "Try". I have coded a simple method below that retrieves roomInformation from a dictionary (roomInformation is a class) and then prints it if it exists as well as returns true.

Have I done this right? is there a better way? please do let me know if a more robust alternative solution exist.

public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
if (!_roomInformation.ContainsKey(roomId))
{
roomInformation = null;
return false;
}

if (_roomInformation.TryGetValue(roomId, out roomInformation))
{
return true;
}

roomInformation = null;
return false;
}


Useage:

RoomInformation roomInfo;
if (!RoomManager.TryGetRoomInformation(1, out roomInfo))
{
// didnt find anything :(
return;
}

// use roomInfo, it was found

• This doesn't look right. Can you post the entire code? It's not possible to review this small snippet. – t3chb0t Oct 26 '16 at 16:49
• Have you considered using locks? Or a transactional database? – CodesInChaos Oct 27 '16 at 9:41
• There's nothing specific to concurrent dictionaries here. TryGetValue is part of the IDictionary<TKey, TValue> interface. – Peter Taylor Nov 25 '16 at 18:39

One thing I noticed, you can eliminate the first if block, that condition is handled later. If the key is invalid TryGetValue will return false and this way you only lookup the key once:

public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
if (_roomInformation.TryGetValue(roomId, out roomInformation))
{
return true;
}

roomInformation = null;
return false;
}


Worked out the best way of doing this is like this...

public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
return _roomInformation.TryGetValue(roomId, out roomInformation);
}

• One difference is, you're not specifically setting roomInformation to null – tinstaafl Oct 26 '16 at 16:17
• Its initially set to null because no parameter is actually passed, its just declared, so roomInformation's default = null. – Liam Oct 26 '16 at 16:20
• One caveat to that is, that in the future it would be easy to forget that and actually pass a RoomInformation object that isn't null. Specifically forcing it to null would cover that eventuality. – tinstaafl Oct 26 '16 at 18:20
• It will not contain the old value, since out parameter must be set by called method. This is enforced by compiler. And as with other TryX methods, TryGetValue sets out parameter to default(T) if operation failed. – Nikita B Oct 27 '16 at 7:32
• If it is down to one line then might as well inline it. – paparazzo Oct 28 '16 at 11:56