Click here to Skip to main content
15,936,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a simple question:
can i explicitly cast an object array to an int array?

probably not because the object array can contain floats or longs etc..
Updated 25-Apr-18 20:38pm

Look at ConvertAll. That allows you to specify a function to perform the conversion. Since you indicated the array may contain non-integer data types (such as float), you will need to perform an explicit cast to truncate the values.
Share this answer
AspDotNetDev 16-Sep-10 15:37pm    
Also, this works with the .Net Framework 2.0, so it's more flexible than the generic Cast method.
Samuel Cherinet 16-Sep-10 15:48pm    
alright!!! must say this is a better approach, you learn something new everyday. Thanks!
You can't convert an integer array into an object array. But you can do the following:

object[] a = new object[] { (int)1, (int)2 }

object b = (object)(new int[] { 1, 2 })


Sorry, getting turned around by your question not matching your original title.

But ultimately, it follows the inverse of the above rules. You can cast the contents of an object array to an integer. You can't just do it directly with the reference of the object array. You have to iterate over each of the objects and cast them one at a time.
Share this answer
if you are using .net 3.5 this might help you
object[] objarr = new object[] {1,2,3 };
 int[] arr= objarr.Cast<int>().ToArray();

its a neat method included with .net 3.5 that allows you to cast the entire collection.

Hope that helped
good luck
Share this answer
AspDotNetDev 16-Sep-10 15:28pm    
This will not work, as the OP indicated the array may contain other types that can't be directly assigned to an int, such as a float, which would require an explicity cast. Try using 5.5 instead of 1 in your array.
Member 11058486 4-Sep-14 6:57am    
this solution are not working so erase it,and give right solution
Member 11058486 4-Sep-14 7:01am
on this page when i page up and down ,your theam are spreads so coorect it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900