Besides the fact that you look very strange, there is nothing wrong with that - technically. First, a trader declaration will be declared, so there is a Trader object without an assigned value. Secondly, the TryGetValue part is evaluated and returns either true or false. If he returns, the now assigned trader returns. If it returns false, a new trader is created and added to the dictionary through the assignment operation. The result of the assignment operation is the value of the object to which it was assigned. This is a new trader. Third, the result of the ternary operator will be returned and assigned to trader .
It is unlikely that this will change in the future, because a change in the evaluation order of such a statement changes dramatically.
UPDATE:
Because it looks very strange, I would not use it. I would solve this problem by creating an extension method for IDictionary<TKey, TValue> called GetOrAdd .
It might look like this:
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> creator) { TValue value; if(!dict.TryGetValue(key, out value)) { value = creator(key); dict.Add(key, value); } return value; }
You would call it like this:
var trader = traderSet.GetOrAdd(key, k => new Trader(s.gateway, s.broker));
This cleaner is a lot and it is even shorter than your weird approach.
BTW: You can use ConcurrentDictionary<TKey, TValue> . This class already has a GetOrAdd method and has the advantage of thread safety.
source share