Today I tested the following code in Visual Studio 2010 (.NET Framework version 4.0)
Type[] interfaces = typeof(int[]).GetInterfaces();
And I was shocked to find these two on the list:
System.Collections.Generic.IReadOnlyList`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Collections.Generic.IReadOnlyCollection`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
I have used these two interfaces before in environments with framework 4.5+ installed, and according to the documentation, both of them were created for 4.5. This does not compile in my environment:
System.Collections.Generic.IReadOnlyList<int> list = new int[3];
The type or namespace name 'IReadOnlyCollection' does not exist in the namespace 'System.Collections.Generic' (are you missing an assembly reference?)
When I try this:
int[] array = new int[3];
Type iReadOnlyCollection = Type.GetType("System.Collections.Generic.IReadOnlyCollection`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
int count = (int)iReadOnlyCollection.GetProperty("Count").GetValue(array, null);
count
equals 3, as expected. What is going on here?
Edit: I do not think framework 4.5 is installed on my machine:
Edit 2: Thanks @ScottChamberlain, it turns out I did have it installed.
.NET 4.5 is an in-place update for .NET 4. This means that while in visual studio you cannot reference IReadOnlyCollection<T>
while targeting .NET 4, the runtime has this type available if you have the 4.5 update installed.
Try running your code in an environment where you don't have the .NET 4.5 update (i.e., just 4.0) and the code will not find the interface type. I.e., Type.GetType("System.Collections.Generic.IReadOnlyCollection`1...
would return null
, and typeof(int[]).GetInterfaces()
will not contain the interfaces you mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With