How can I introduce int [] interfaces that do not yet exist (for me)?

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 = b77a5c561934

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 = b77a5c561934

I used these two interfaces before in environments with the 4.5+ framework installed and according to the documentation and of they 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' (do you miss the assembly link?)

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 is 3, as expected. What's going on here?

Edit: I don’t think the framework 4.5 is installed on my computer:

Edit 2: Thanks @ScottChamberlain, it turned out that I installed it.

+5
source share
2 answers

.NET 4.5 is an in-place update for .NET 4 . This means that while in visual studio you cannot reference IReadOnlyCollection<T> when targeting .NET 4, the runtime is of this type if you have update 4.5 installed.

Try running the code in an environment where you do not have the .NET 4.5 update (i.e., a total of 4.0) and the code does not find the interface type. Ie, Type.GetType("System.Collections.Generic.IReadOnlyCollection`1... will return null , and typeof(int[]).GetInterfaces() will not contain the interfaces you specify.

+6
source

You are compiling for .NET 4.0, so 4.5-specific types are not considered by the compiler.

You are running on .NET 4.5 or 4.6, so 4.5-specific types are scanned by the runtime.

If you expected your application to run on .NET 4.0, you won’t be able to ..NET 4.5 and 4.6 β€” in-place updates. After installation, your system no longer has .NET 4.0. You can still run .NET 4.0 applications, since .NET 4.5 and 4.6 are pretty much feedback compatible and that the runtime will just be used instead.

+4
source

All Articles