0

The next code from the book "Pro-linq language itegrated query in C# 2008" gives a casting exception error on line 29. I know ToArray returns an array of objects, which are in fact of type Employee so why it generates an error?

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()
            {
                /** my commented code works **/
                //ArrayList al = GetEmployeesArrayList();
                //Employee[] emp = new Employee[al.Count];
                //for (int i = 0; i < al.Count; i++)
                //{
                //    emp[i] = (Employee)al[i];
                //}
                //return emp;
                /*** next line(original code) gives InvalidCastException ***/
                return ((Employee[])GetEmployeesArrayList().ToArray());
            }
        }
2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by ddanbe
1

When you add it to the ArrayList it's losing all it's typing information. You need to tell it what type it is as you cast it:

return (Employee[])GetEmployeesArrayList().ToArray(typeof(Employee));

And the updated version of that book is one of my "read next" items :)

Edited by Momerath: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.