Since .NET arrays are covariant, the following works in C#:
var strArray = new string[0];
object[] objArray = strArray;
In F#, given an array, 'T[]
, what would be the best way to convert it to obj[]
, without re-creating the array (e.g., Array.map box
)? I'm using (box >> unbox)
, but it feels sloppy.
As Brian says, there's nothing wrong with box >> unbox
, other that the fact that array covariance is inherently broken (e.g. ([| "test" |] |> box |> unbox<obj[]>).[0] <- obj()
will throw an ArrayTypeMismatchException when trying to perform the assignment).
Instead, you would probably be better off treating a string[]
as an obj seq
, which is perfectly safe (although it still requires boxing and unboxing in F# since F# doesn't support generic co/contra-variance). Unfortunately, you do lose random access if you go this route.
box >> unbox
seems like a good idea; O(1), and does the job, apparently.
Consider also not using this CLR mis-feature. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With