public static ArrayList GetStudentAsArrayList()
{
ArrayList students = new ArrayList
{
new Student() { RollNumber = 1,Name ="Alex " , Section = 1 ,HostelNumber=1 },
new Student() { RollNumber = 2,Name ="Jonty " , Section = 2 ,HostelNumber=2 }
};
return students;
}
The following code doesn’t compile. The error is ArrayList is not IEnumerable
ArrayList lstStudents = GetStudentAsArrayList();
var res = from r in lstStudents select r;
This compiles:
ArrayList lstStudents = GetStudentAsArrayList();
var res = from Student r in lstStudents select r;
Can anybody explain what the difference is between these two snippets? Why the second works?
Since ArrayList allows you to collect objects of different types, the compiler doesn’t know what type it needs to operate on.
The second query explicitly casts each object in the ArrayList to type Student.
Consider using
List<>instead of ArrayList.