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