The generic dictionary is as follows:
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>
And specific dictionaries can be as follows:
var container = new ConcurrentDictionary<string, Unit>();
var container = new ConcurrentDictionary<string, CustomUnitClass>();
These special dictionaries (with different parameters) have been added in Application state:
HttpContext.Current.Application[key] = container;
When I get the items from Application state (some people here helped me about that; Thanks them), I’m able to check if type is of ConcurrentDictionary in this way:
object d = HttpContext.Current.Application[i];
if (d.GetType().GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>))
And the last point was left – how to cast object d to generic ConcurrentDictionary:
ConcurrentDictionary<?, ?> unit = d as ConcurrentDictionary<?, ?>;
I don’t want to use specific cast as follows:
ConcurrentDictionary<string, Unit> unit = d as ConcurrentDictionary<string, Unit>;
because the second parameter can be of another type.
Thank you in advance.
I think you might be looking at generics in a slightly wrong way, but that’s okay, lets talk!
Your
IDictionary<TKey, TValue>is perfect, and you’re using it correctly, however I think when it comes to casting back, unless you explicitly know what the type is you’re expecting, there’s no real point in casting it.Alternatively what I would recommend, for the purpose of strongly-typed loveliness; you mentioned that potentially the second type, aka the
TValuewill vary… this is a perfect time to use an interface! Let me demonstrate.Our interface
Our objects
Our implementation
Let’s take a break
As you can from the above, we have a dictionary with a key type of
stringand a value type ofIModeOfTransport. This allows us explicit strongly-typed access to all of the properties and methods of theIModeOfTransportinterface. This is recommended if you need to access specific information on a generic value within a dictionary, and you don’t know what the actual object type cast is. By using interfaces it allows us to find similarities.Almost done