How Arrays in C# Partially Implement IList
Despite not publicly declaring the Count property of IList, arrays in C# can be considered to partially implement the interface.
Implementation Details
Although arrays do not directly implement IList, the Common Language Runtime (CLR) creates a concrete array type that does indeed implement the interface. However, this implementation is not apparent through traditional means.
Specifically, the CLR uses a system-defined class called System.SZArrayHelper to provide the underlying implementation of IList for arrays. This implementation includes the Count property, which internally delegates to the Length property of the array.
Example of Use
To cast an array to IList, the compiler generates IL code that performs a cast using the castclass instruction. The CLR then utilizes the SZArrayHelper class to provide the interface implementation.
Limitations
The partial implementation of IList by arrays comes with some limitations. For instance, attempting to invoke the GetInterfaceMap method on an array type with the interface parameter set to IList will result in an "Interface not found" exception.
Implications
The implementation of IList by arrays through SZArrayHelper is a case of quacks-like-a-duck typing, where the CLR provides the illusion that the array implements the interface even though it doesn't explicitly do so. This allows for arrays to be used as IList objects without requiring a custom adapter.
The above is the detailed content of How Do C# Arrays Partially Implement the IList Interface?. For more information, please follow other related articles on the PHP Chinese website!