Search code examples
c#.netclrmef

Is a generic type MyType<,> actually a type?


I have some confusion with this that arose from messing around with exporting generic types in MEF

I noticed:

new Dictionary<string,bool>().GetType() == typeof(Dictionary<,>)
false
new Dictionary<string,bool>().GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)
true

Yet Dictionary<,> itself is not considered a ‘type’ as this will actually generate a compile error:

new Dictionary<string,bool> as Dictionary<,>
Type expected
new Dictionary<string,bool> is Dictionary<,>
Type expected

So my question is, is Dictionary<,> actually a type? Does .NET treat generic types differently than non-generic types?

Now in MEF I can export a generic class as

[Export(typeof(MyGenericClass<,>))]

And this would satisfy an import requirement like

[Import]
public MyGenericClass<string, long> Instance { get; set; }

I'm confused about the type-system's rules here


Solution

  • See What exactly is an “open generic type”. What you are referring to is called an unbound generic type and is explained in the same post. An unbound generic type is actually a type, however it can only be used within a typeof() expression. Note: Unlike C# Java allows expressions like List<?>.