1

(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];

   //             }
            }
2
  • You expected that studentarraylist is the list of Student, but i saw you cast object to Course??? Commented Apr 27, 2015 at 13:40
  • 1
    my code might not be super clean - I was trying a few things. I was trying to add the items in Course but it didn't work and added them in main instead. I was trying to cast them to original type but got no where. Commented Apr 27, 2015 at 13:43

4 Answers 4

5

You should not be using ArrayList for this, to begin with. Generic List<Student> is what you need for your list here.

However if you have to stick to ArrayList, it does not contain any Course objects, only Student ones. So the first cast should fail:

(Course)studentarraylist[0]

Now, if you want to call student specific methods on the items of the list, you need to make sure to cast them to correct type, Student in this case:

for (int i = 0; i < studentarraylist.Count; ++i)
{
    Student s = (Student)studentarraylist[i];
    ...
}

Also, if you want to iterate over students you've already added, you do not need to pass anything to liststudents - you already have a field in the class instance to work with. So it should be

public void liststudents()
{
    for (int i = 0; i < studentarraylist.Count; ++i)
    {
        Student s = (Student)studentarraylist[i];
        ...
    }
}

And the usageof the Course class:

Course c = new Course();
c.AddStudent(student1);
c.AddStudent(student2);
c.liststudents();

Last thing - unless there is a hard reason to do so, do not use no-caps names like liststudents. It should be ListStudents according to C# standards.

Sign up to request clarification or add additional context in comments.

Comments

2

Your question is a little confusing, but it looks like your liststudents() is the problem. When you pull an items off of your studentarraylist you should be casting it into a Student object, and not a Course object.

EDIT

Take out the paramenter from the liststudents(), because your Course class already has the ArrayList defined in it. You shouldn't have to pass an ArrayList to your class that your class already knows about.

public void liststudents()
{
    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.
    }
}

Then you would use liststudents() from main like so...

Course myCourse = new Course();
myCourse.AddStudent(someNewStudentYouMade);
myCourse.AddStudent(someNewStudentYouMade);
myCourse.AddStudent(someNewStudentYouMade);
myCourse.AddStudent(someNewStudentYouMade);
myCourse.AddStudent(someNewStudentYouMade);
myCourse.liststudents();

4 Comments

that sort of looks right but I am still getting my head around it. it looks like it is casting to orignal type and then printing out first and last name !! - what would I pass in to course.liststudents(); ?
@Aindriu I thought the liststudents() was in your Course class? Can you post your Course class and Student class?
Yes it is in Course but I was calling the method course.liststudent() from main.
wow ! that worked. I just hope it is casting before printing out
1

In your for-loop, you're not actually printing out the student, but the entire list.

One way to solve this is just print out the name of the student at the position i like this:

for (int i = 0; i < studentarraylist.Count; ++i)
    {
         Console.WriteLine("student first name", studentarraylist[i].Name.ToString());
         Console.WriteLine("");
    }

4 Comments

Since the OP is using an ArrayList, it's probably not a good idea to use a foreach to iterate through the ArrayList, because there is no guarantee that all objects in the ArrayList are of type Student.
they are all of type student and I need to use the foreach loop
@Shar1er80 You're right, i'll remove that part from my answer. However, OP should be using a List<Student> as the top answer says.
Then as @Andrei has suggested, you should be using a List<> from the System.Collections.Generic namespace. You would have a List<Student> inside your Course class, then you wouldn't have to bother with any casting.
1

Using foreach - implicit cast

If it's in main

foreach (Student student in MyCourseObject.Students)
{
    Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
}

If inside Course class

public void ListStudents()
    {
        foreach (Student s in this.Students)
        {
           Console.WriteLine("{0} {1}", s.FirstName, s.LastName);
        }
    }

Using for loop - explicit cast

In main

for (int i = 0; i < MyCourseObject.Students.Count; i++)
{
    Student student = (Student)MyCourseObject.Students[i];
    Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
}

If inside Course Class

public void ListStudents()
    {
         for (int i = 0; i < this.Students.Count; i++)
         {
             Student student = (Student)this.Students[i];
             Console.WriteLine("{0} {1}", student.FirstName, student.LastName);
         }
     }

for this assume that:

  • There is a Student ArrayList defined in the Course Class.

  • MyCourseObject is an Instance of Course class.

  • Students is the Arraylist which contains objects(instances) of type Student.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.