C#中Array与object[]的区别及Enum.GetValues()返回Array的原因
Great question—this digs into some of the .NET framework's foundational design choices, especially around cross-compatibility and type flexibility. Let's break this down step by step:
1. The Core Reason: Value Type Enums and Array Compatibility
First, remember that enums are value types in .NET. When you call Enum.GetValues(typeof(MyEnum)), it doesn’t return an object[]—it returns a strongly-typed array of your enum type, e.g., MyEnum[].
Here’s the catch: value-type arrays (like MyEnum[] or int[]) can’t be directly cast to object[]. Unlike reference-type arrays (which inherit from object[]), value-type arrays are a separate branch of the Array inheritance tree. If Enum.GetValues() tried to return object[], it would have to box every enum value individually, adding unnecessary overhead and breaking the strongly-typed nature of the result.
System.Array is the abstract base class for all array types in .NET—both value-type and reference-type arrays inherit from it. Returning Array lets the method hand back the actual strongly-typed enum array without boxing, while still providing a common interface to work with the collection.
2. COM Visibility: A Historical Context
You’re right to connect this to ComVisible! Back in the early days of .NET, seamless integration with COM was a top priority. System.Array is marked with [ComVisible(true)], making it accessible to COM clients.
In contrast, while object[] is also COM-visible, returning a generic or specific value-type array (like MyEnum[]) would be problematic for COM, which doesn’t understand .NET’s strong typing in the same way. Using Array as the return type ensures that COM code can interact with the result reliably, without having to handle .NET-specific type nuances.
3. Are Array and object[] Instances the Same?
Short answer: No, they’re not interchangeable, even if their public methods/properties look similar. Here’s why:
Arrayis the abstract base class for all arrays. It can represent any array type (value-type, reference-type, multi-dimensional, etc.).object[]is a concrete, reference-type array that can only hold objects (boxed value types or reference types). You can’t assign aMyEnum[]directly to anobject[]variable—you’d have to explicitly box each element first, which creates a new array of boxed values.- Under the hood, their memory layouts differ: value-type arrays store values directly in contiguous memory, while
object[]stores references to objects on the heap.
Wrapping Up
Enum.GetValues() returns Array instead of object[] for two key reasons:
- It preserves the strongly-typed value-type array of the enum, avoiding unnecessary boxing overhead.
- It maintains compatibility with COM, a critical requirement for .NET’s early adoption.
You can easily convert the Array result to a strongly-typed array if needed, using code like:
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
内容的提问来源于stack exchange,提问作者Gusty Abra

