I have a class that contains something like this Dictionary<int, Queue<string>> dict and then I use TryGetValue:
Queue<string> value;
if (!dict.TryGetValue(3, out value))
throw new MyException("...");
Is there an option not to explicitly define the value type, basically to avoid duplicity of typing it? In C++ STL containers, there is a value typedef value_type which can be used in such cases but I can’t seem to find similar feature in C#. Thanks.
If you define yourself a nice helper method, you can wrap up the type specification:
Notice here we still have to explicitly type the value that’s going to be populated by
TryGetValue, BUT from your caller you can just say:Note that if
nullis a valid value in this context, you’ll need something else, but the same principle could be applied – use the fact that the compiler can infer types for generic methods to build a helper method to hide the explicit typing.