How to convert object[] to a more specifically typed array
You can't perform such a cast, because the arrays object[] and string[] are actually different types and are not convertible. However, if you wanted to pass different such types to a function, just make the parameter IEnumerable. You can then pass an array of any type, list of any type, etc.
// Make an array from any IEnumerable (array, list, etc.)
Array MakeArray(IEnumerable parm, Type t)
{
if (parm == null)
return Array.CreateInstance(t, 0);
int arrCount;
if (parm is IList) // Most arrays etc. implement IList
arrCount = ((IList)parm).Count;
else
{
arrCount = 0;
foreach (object nextMember in parm)
{
if (nextMember.GetType() == t)
++arrCount;
}
}
Array retval = Array.CreateInstance(t, arrCount);
int ix = 0;
foreach (object nextMember in parm)
{
if (nextMember.GetType() == t)
retval.SetValue(nextMember, ix);
++ix;
}
return retval;
}
It's not really a cast as such (I'm allocating a new array and copying the original), but maybe this can help you out?
Type myType = typeof(string);
object[] myArray = new object[] { "foo", "bar" };
Array destinationArray = Array.CreateInstance(myType, myArray.Length);
Array.Copy(myArray, destinationArray, myArray.Length);
In this code, destinationArray
will be an instance of string[]
(or an array of whatever type myType
was).
This is not a one liner but it can be done with two lines. Given your specified Array
of elements of the correct type myArray
and the specified Type
parameter myType
, dynamically calling .Cast<"myType">.ToArray()
would work.
var typeConvertedEnumerable = typeof(System.Linq.Enumerable)
.GetMethod("Cast", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(new Type[] { myType })
.Invoke(null, new object[] { myArray });
var typeConvertedArray = typeof(System.Linq.Enumerable)
.GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(new Type[] { myType })
.Invoke(null, new object[] { typeConvertedEnumerable });
While the method generation is slower than a direct call, it is O(1) on the size of the array. The benefit of this approach is, if IEnumerable<"myType">
would be acceptable, the second line is not needed, and therefore I do not believe the array will be copied.