Get the key type of a Dictionary

L

Luigi

Hi all,
using C# 2.0, is there a way to get the type of the keys on a generic
dictionary?

For example, if I have a dictionary like this:

Dictionary<MyObject1, MyObject2> testDic = new Dictionary<MyObject1,
MyObject2>();

I'd like to get MyObject1.

Thanks in advance.
 
A

Anthony Jones

Luigi said:
Hi all,
using C# 2.0, is there a way to get the type of the keys on a generic
dictionary?

For example, if I have a dictionary like this:

Dictionary<MyObject1, MyObject2> testDic = new Dictionary<MyObject1,
MyObject2>();

I'd like to get MyObject1.


Try this:-

Type[] dictTypes = testDic.GetType().GetGenericArguments();
Type keyType = dictTypes[0];
Type valueType = dictTypes[1];
 
J

Jeff Johnson

using C# 2.0, is there a way to get the type of the keys on a generic
dictionary?

For example, if I have a dictionary like this:

Dictionary<MyObject1, MyObject2> testDic = new Dictionary<MyObject1,
MyObject2>();

I'd like to get MyObject1.

You mean you'd like to get the TYPE of MyObject1? Well, since I've been
playing with it recently, I can tell you the long way*: use Reflection.

Air code:

Type keyType = null;
Type dicType = testDic.GetType();
foreach (Type argType in dicType.GetGenericArguments())
{
if (argType.GenericParameterPosition == 0)
{
keyType = argType;
break;
}
}



* Whether there's a shorter way than this I don't know.
 
L

Luigi Zambetti

Anthony Jones said:
Try this:-

Type[] dictTypes = testDic.GetType().GetGenericArguments();
Type keyType = dictTypes[0];
Type valueType = dictTypes[1];

Well done, thank you Anthony.

Luigi
 
J

Jeroen Mostert

Anthony said:
Luigi said:
Hi all,
using C# 2.0, is there a way to get the type of the keys on a generic
dictionary?

For example, if I have a dictionary like this:

Dictionary<MyObject1, MyObject2> testDic = new Dictionary<MyObject1,
MyObject2>();

I'd like to get MyObject1.


Try this:-

Type[] dictTypes = testDic.GetType().GetGenericArguments();
Type keyType = dictTypes[0];
Type valueType = dictTypes[1];
This is the statically typed equivalent, which may or may not be more
appropriate depending on what you're doing:

void Foo<TKey, TValue>(Dictionary<TKey, TValue> dict) {
Type keyType = typeof(TKey);
Type valueType = typeof(TValue);
...
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top