What is the easiest way to cast an object array to an integer array?
ArrayList al = new ArrayList();
object arrayObject = al.ToArray();
int[]arrayInteger = ?
Thanks
Use int[]arrayInteger = (int[])al.ToArray(typeof(int));
But unless you are using .Net 1.1, user a List<int> instead.
You could use Array.ConvertAll
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => (int)o);
One thing to consider is since this is an object array all the values may not be int
This is the handy thing about ConvertAll as you can add simple conversion logic to catch errors.
Scenario:
ArrayList al = new ArrayList() { 1,"hello",3,4,5,6 };
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => { int val = -1; return int.TryParse(o.ToString(), out val) ? val : -1;});
This way we can perform a TryParse on the object to avoid any InvalidCastException due to bad data.