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());
            }
        }

Recommended Answers

All 2 Replies

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 :)

Thanks Momerath, for the clarification.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.