Home > Backend Development > C++ > Why Don't C# Arrays Directly Implement `IList`, and How Do They Still Seem To?

Why Don't C# Arrays Directly Implement `IList`, and How Do They Still Seem To?

Mary-Kate Olsen
Release: 2025-01-04 17:56:39
Original
251 people have browsed it

Why Don't C# Arrays Directly Implement `IList`, and How Do They Still Seem To?

Arrays in C#: A Deeper Dive into Interface Implementation

Although arrays in C# appear to implement IList, they do not publicly expose the Count property. This may seem like a contradiction to C# interface implementation rules.

In reality, arrays implement System.Collections.IList, not System.Collections.Generic.IList. Generic interfaces like IList cannot be implemented by non-generic types like Array.

However, the CLR generates specific array types that could potentially implement these interfaces. But even for these concrete array types, casting to IEnumerable works, while retrieving the interface map throws an exception.

This is due to "quacks-like-a-duck" typing, where the compiler and CLR recognize arrays as implementing IList. The cast instruction is handled by a hidden wrapper class System.SZArrayHelper that provides an implementation of IList over the array.

Even though the Count property is not explicitly implemented, the CLR provides an internal getter using a cast to the T[] array.

This behavior, while somewhat unconventional, allows for a seamless and efficient implementation of IList for arrays. It's a clever technique that showcases the hidden mechanisms in C# and the CLR that contribute to its flexibility and power.

The above is the detailed content of Why Don't C# Arrays Directly Implement `IList`, and How Do They Still Seem To?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template