(this is an academic problem)
I created an Arraylist to hold student objects. Now I need to cast them back to original type and print out on the console. I need to create a method in an object that would loop through all objects (after they have been cast back) and print them out -
How do I cast a returned object from the ArrayList to a (Student) object.
In course object I created an ArrayList called studentarraylist
public class Course
{
ArrayList studentarraylist = new ArrayList();
In that course object I created a method to add student
public void AddStudent(Student student)
{
studentarraylist.Add(student);
}
In main - I added a student object to the ArrayList using that method
course.AddStudent(student1);
Now I need to create a method in Course to cast objects back to original type, using a foreach loop iterate over the Students in the ArrayList and output their first and last names to the console window. I got a bit mixed up as I don't have access to some items in the method - when I created them in main.
public void liststudents(ArrayList studentarraylist)
{
Course studentoneout = (Course)studentarraylist[0];
for (int i = 0; i < studentarraylist.Count; ++i)
{
//Console.WriteLine(studentarraylist[i]);
Console.WriteLine("student first name", studentarraylist.ToString());
Console.WriteLine("");
}
}
edit ***
public class Course
{
ArrayList studentarraylist = new ArrayList();
private string courseName;
//Create a course name
public string CourseName
{
get { return courseName; }
set { courseName = value; }
}
//add student method
public void AddStudent(Student student)
{
studentarraylist.Add(student);
}
public void liststudents(ArrayList studentarraylist)
{
for (int i = 0; i < studentarraylist.Count; i++)
{
Student currentStudent = (Student)studentarraylist[i];
Console.WriteLine("Student First Name: {0}", currentStudent.FirstName); // Assuming FirstName is a property of your Student class
Console.WriteLine("Student Last Name: {0}", currentStudent.LastName);
// Output what ever else you want to the console.
}
// Course studentoneout = (Course)studentarraylist[0];
// for (int i = 0; i < studentarraylist.Count; ++i)
// {
// Student s = (Student)studentarraylist[i];
// }
}