dotnet / dotnet/runtime

`ComVariant.As<T>` does not support `VT_ARRAY` variants

Open
#122,109 8 comments 0 reactions 0 assignees View on GitHub
area-Interop-coreclr
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

Today, the [`ComVariant.As()`](https://github.com/dotnet/runtime/blob/fed27579999347f09206eff7eab6026e6e676077/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshalling/ComVariant.cs#L444) function supports many types, but not arrays (`VT_ARRAY`). We should update the function to support these common types.

### Reproduction Steps

1. Create or consume an API that generates an array variant. For example, `IUIAutomationElement..GetCurrentPropertyValue(UIA_PROPERTY_ID.UIA_RuntimeIdPropertyId)` returns [a `VT_I4 | VT_ARRAY`](https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-automation-element-propids#:~:text=cache.%0AVariant%20type%3A-,VT_I4%20%7C%20VT_ARRAY,-Default%20value%3A)
2. Try to "cast" the variant into a managed type, e.g. `.As()` or `.As()`.

This throws an `ArgumentException`. Instead, callers must parse the raw value manually: see [my use](https://github.com/citelao/AccView/blob/e109c8f7ed3d0837ad435aeda0060370ccc035db/AccView/ViewModels/AutomationElementViewModel.cs#L114C35-L114C100); I wrote an extension method [`ComVariant.AsArray()`](https://github.com/citelao/AccView/blob/e109c8f7ed3d0837ad435aeda0060370ccc035db/Shared/ComVariantExtensions.cs#L28-L44) where I do such parsing.

### Expected behavior

First:

1. `ComVariant.As` should support `T = int[]` (and `T = SAFEARRAY`).
* Realistically, the function should support arrays of any otherwise-supported type, e.g. `string` ...

Furthermore:

2. `ComVariant.As` should generate a clearer error when an invalid type is passed, AND
3. [MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshalling.comvariant.as?view=net-9.0) should document supported types.

### Actual behavior

This throws an `ArgumentException`.

### Configuration

Repros in .NET 10.0 & .NET 9.0, and probably all other versions.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.