Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList to int[] in c#

I have my declaration as follows

int[] EmpIDs = new int[] { };
ArrayList arrEmpID = new ArrayList();
int EmpID = 0;
if (CheckBox1.Checked)
{
   EmpID = 123;
   arrEmpID.Add(EmpID);
}
if (CheckBox2.Checked)
{
   EmpID = 1234;
   arrEmpID.Add(EmpID);
}
if (CheckBox3.Checked)
{
   EmpID = 1234;
   arrEmpID.Add(EmpID);
}

After all i would like to assign this the EmpIDs which was declared as int array

I tried this

for (int i = 0; i < arrEmpID.Count; i++)
    {
        EmpIDs = arrEmpID.ToArray(new int[i]);
    }

But i am unable to add can any one help me

like image 966
Vivekh Avatar asked Sep 07 '11 07:09

Vivekh


4 Answers

You should avoid using ArrayList. Instead use List<int>, which has a method ToArray()

List<int> list = new List<int>();
list.Add(123);
list.Add(456);
int[] myArray = list.ToArray();
like image 100
Jamiec Avatar answered Nov 13 '22 15:11

Jamiec


When converting an ArrayList to an array, you'll have to specify the type of the objects that it contains, and, you'll have to make sure you cast the result to an array of the desired type as well:

int[] empIds;

empIds = (int[])arrEmpID.ToArray(typeof(int));

But, as pointed out by others, why are you using an ArrayList ? If you're using .NET 1.1, you indeed have no other choice then using an ArrayList. However, if you're using .NET 2.0 or above, you should use a List<int> instead.

like image 40
Frederik Gheysels Avatar answered Nov 13 '22 17:11

Frederik Gheysels


Instead of the (old) ArrayList class, use a (mordern) List<int>. It's type safe and it has a ToArray method:

List<int> arrEmpID = new List<int>(); 
if (CheckBox1.Checked) 
    arrEmpID.Add(1234); 
if (CheckBox2.Checked) 
    arrEmpID.Add(1234); 
if (CheckBox3.Checked) 
    arrEmpID.Add(1234); 

int[] EmpIDs = arrEmpID.ToArray();

In fact, you might consider using the List<int> all along instead of creating an int[] afterwards.

like image 24
Heinzi Avatar answered Nov 13 '22 15:11

Heinzi


If you really need ArrayList, you can try using the following:

EmpIDs = arrEmpID.OfType<int>().ToArray();

(But this is only available in .NET 3.5 and above)

like image 1
Stephan Bauer Avatar answered Nov 13 '22 17:11

Stephan Bauer