c# - where do arrays inherit from (i.e .int[] )
When creating an array, such as int[], does this inherit from anything? I thought it might inherit from System.Array, 开发者_运维问答but after looking at the compiled CIL it does't appear so.
I thought it might inherit from System.Array or somehting similair, considering you can call methods and access properties on an array.
I.e.
int[] arr = {1, 2};
arr.Initialize();
arr.Length;
All arrays derive from System.Array
. From an (admittedly ancient) edition of MSDN magazine:
All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.
From section 19.1.1 of the C# Language Specification (emphasis mine):
The type System.Array is the abstract base type of all array types. An implicit reference conversion (§13.1.4) exists from any array type to System.Array and to any interface type implemented by System.Array. An explicit reference conversion (§13.2.3) exists from System.Array and any interface type implemented by System.Array to any array type. System.Array is not itself an array-type. Rather, it is a class-type from which all array-types are derived.
An array does inherit from System.Array
. It's a specialisation of a generic type, kind of like System.Array<int>
, except that the runtime treats arrays as "special" - they are a special case of generics that existed in .NET 1.0 before the "general" generics were introduced in .NET 2.0.
Edit: Just checked my answer using Reflection and it looks like the base type of an array actually is System.Array
. Corrected.
One thing I found interesting is that arrays also implements ICollection<>
int[] foo = new int[]{ };
ICollection<int> bar = foo;
// So, arrays would have type infered to use ICollection<> overload
IEnumerable<T> Foo<T>(Func<IEnumerable<T>> bar); // .Count()
ICollection<T> Foo<T>(Func<ICollection<T>> bar); // .Count
精彩评论