Reputation: 12077
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...
Upvotes: 3
Views: 4327
Reputation: 700262
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()
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()
Upvotes: 7
Reputation: 5269
I might be missing a part of the context but from your example, the problem isn't the cast itself but the way you create your object.
Instead of creating an object, you should create an object array.
Dim obj As Object() = {1, 2, 3} 'integer array
Dim objArr As Object() = obj
However, if you can't apply this in your context, then Guffa's answer is the way to go.
Upvotes: 0
Reputation: 3112
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())
Upvotes: 1