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
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();
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With