Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a generic type MyType<,> actually a type? [duplicate]

Tags:

c#

.net

clr

mef

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

like image 225
blue18hutthutt Avatar asked Mar 05 '26 21:03

blue18hutthutt


1 Answers

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<?>.

like image 100
Olivier Jacot-Descombes Avatar answered Mar 08 '26 11:03

Olivier Jacot-Descombes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!