Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an Object to an Object Array

Tags:

.net

vb.net

What is the proper syntax for casting an object to an Object(). Here's an example:

Dim obj as Object = {1,2,3}   'integer array or array of anything
Dim objArr as Object() = CType(obj, Object())

I can't seem to find the correct way to do this...

like image 397
Denis Avatar asked Aug 08 '26 15:08

Denis


2 Answers

There is no syntax for that, as it's not possible. You can't cast an integer array to an object array, because an integer is not an object.

Casting the object reference to an integer array reference works fine:

Dim objArr As Integer() = CType(obj, Integer())

You can cast each integer in the array to an object to create an object array with the values from the integer array:

Dim objArr As Object() = CType(obj, Integer()).Cast(Of Object)().ToArray()

Edit:

As you edited your question to include any type of array, not just an integer array, casting to IEnumerable as you suggested works fine as any type can still be cast to Object in the next step:

Dim objArr As Object() = CType(obj, IEnumerable).Cast(Of Object)().ToArray()
like image 103
Guffa Avatar answered Aug 11 '26 09:08

Guffa


As far as I know, you can't just cast an array of Integer to an array of Object.

You can cast to an array:

Dim objArr As Array = CType(obj, Array)
Dim objArr2 As Object() = objArr.OfType(Of Object)().ToArray()

Or you can use Array.ConvertAll:

Dim objArr As Object() = Array.ConvertAll(Of Integer, Object)(obj, Function(t) t)

Or you can cast to an array of Integer, which is what it really is:

Dim objArr as Integer() = CType(obj, Integer())
like image 39
pmcoltrane Avatar answered Aug 11 '26 07:08

pmcoltrane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!