Tags

Today, I followed the book to write following code

    public class Employee
    {
        public int id;
        public string firstName;
        public string lastName;
        public static ArrayList GetEmployeesArrayList()
        {
            ArrayList al = new ArrayList();
            al.Add(new Employee { id = 1, firstName = “Joe”, lastName = “Rattz” });
            al.Add(new Employee { id = 2, firstName = “William”, lastName = “Gates” });
            al.Add(new Employee { id = 3, firstName = “Anders”, lastName = “Hejlsberg” });
            al.Add(new Employee { id = 4, firstName = “David”, lastName = “Lightman” });
            al.Add(new Employee { id = 101, firstName = “Kevin”, lastName = “Flynn” });
            return (al);
        }

        public static Employee[] GetEmployeesArray()
        {                          
                return ((Employee[])GetEmployeesArrayList().ToArray();
        }
    }

But it throws exception when calling GetEmployeesArray at run time with message:Unable to cast object of type ‘System.Object[]’ to type ‘Employee’.

Digging the internet and found you need to use

To perform conversions from object array to an ArrayList use the ArrayList.Adapter method. This method takes an IList to be wrapped into an ArrayList. Now the procedure above can be coded like this:
Person[] personArray = myPerson.GetPersons();

ArrayList personList = ArrayList.Adapter(personArray);

To perform conversions from ArrayList  to object array use the ArrayList.ToArray method. Now the procedure above can be coded like this:
Person[] personArrayFromList = (Person[])personList.ToArray(typeof(Person));

Don’t forget the casting preceding the arraylist.ToArray method, otherwise you’ll get an error message at compile time saying you can’t convert that arraylist into Person array.

Advertisements