-2

I am learning a MOOC course on c#. we had to create an Arraylist of type students and then using the foreach loop had to iterate over it and print the names. i have tried all casting methods but could not get through it. please help

c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);

foreach(object o in students)
{
    Student s = (Student)o;
    Console.WriteLine(s.FirstName);
}

c is the course object. course is a class. students is the arraylist. Student is a class.

Ghasem
  • 14,455
  • 21
  • 138
  • 171
user5538704
  • 91
  • 1
  • 12
  • foreach(var o in student){ Student s=(student)o; } – Manikandan Selvanathan Jan 24 '16 at 06:18
  • 2
    Shouldn't that be `foreach(object in c.students)`? Also you you be more specific about what isn't working? – shf301 Jan 24 '16 at 06:21
  • var doesn't help. it still gives : unhandled exception system.nullreferenceException object reference not set to an instance of an object – user5538704 Jan 24 '16 at 06:21
  • @shf301 ya i did with c.students only! sorry forgot to include it here. i am not able to cast the returned object from the arraylist to a student object. – user5538704 Jan 24 '16 at 06:23
  • 1
    What line do you get the exception on? – shf301 Jan 24 '16 at 06:23
  • Console.WriteLine(s.FirstName); – user5538704 Jan 24 '16 at 06:25
  • Has every student a "FirstName" set? You can try Console.Write(s.ToString()) and see if it throws an exception. Have you called the constructor for your c.students-list? (c.students = new ArrayList())? – kaliba Jan 24 '16 at 06:30
  • 3
    @user5538704. You don't have a casting issue - that would give an InvalidCastException. You've inserted a null value into your list of students. Are any of student1, student2, or student3 null? – shf301 Jan 24 '16 at 06:32
  • Student s = o as Student; if (s != null ........ – nabuchodonossor Jan 24 '16 at 06:46
  • I think @shf301 got it right, unless there is a mistake in the pasted code. Just put c.students in your foreach loop. – frostedcoder Jan 24 '16 at 07:40
  • i put c.students in foreach loop but it still doesn't work. None of the values are empty. I have pasted my code as an answer. Please check and help @shf301 – user5538704 Jan 24 '16 at 07:48

4 Answers4

1

Not sure where you face the error. Check out my .NET Fiddle here. Code shown below as well. Hope it helps.

using System;
using System.Collections;

public class Program
{
    public static void Main()
    {
        var students = new ArrayList();
        students.Add(new Student() { FirstName = "John", LastName = "Doe" });
        students.Add(new Student() { FirstName = "Richard", LastName = "Roe" });

        foreach(Student s in students)
        {
            Console.WriteLine(s.FirstName);
        }
    }
}

public class Student
{
    public string FirstName {get;set;}
    public string LastName {get;set;}   
}
Channs
  • 2,091
  • 1
  • 15
  • 20
  • doesn't work. I have pasted my code please check and help – user5538704 Jan 24 '16 at 07:47
  • @user5538704 - You need to instantiate `c.students` via `c.students = new ArrayList();` and not `ArrayList students = new ArrayList();`. I guess this was a typo. Further, always use properties in lieu of fields, for more details, refer my older answer [here](http://stackoverflow.com/questions/17186432/what-is-the-advantage-of-using-private-variables-in-c-sharp/17186594#17186594). Also, please remove your answer and move its content as an update into your question. – Channs Jan 24 '16 at 09:59
1

foreach(object o in c.students)

this should do it, its probably a silly mistake

namespace stackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            course c = new course();
            student student1 = new student("a");
            student student2 = new student("b");
            student student3 = new student("c");
            c.students.Add(student1);
            c.students.Add(student2);
            c.students.Add(student3);

            foreach (object o in c.students)
            {
                student s = (student)o;
                Console.WriteLine(s.name);
            }

        }
    }
    class course
    {

       public List<student> students = new List<student>();
    }
    class student
    {
        public string name { get; set; }
        public student(string s)
        {
            name = s;
        }
    }
}
1

ArrayList students = new ArrayList();

This line should be: c.students = new ArrayList(); as mentioned by Channs previously.

As you have written it, it is trying to create a new variable in your main function called students, it never accesses the students array inside your course object.

Although your initialisation of internal object variables should be done within the object itself.

So inside your course object do something more like this:

class Course
{
    public ArrayList students;

    public Course()
    {
        students = new ArrayList();
    }
}  

This way, whenever you declare a new object of type Course ( ie: Course c = new Course() ) it will initialise the array automatically.


Another issue I noticed was in your Student constructor declaration, you are always trying to take a parameter of string fname.

public Student(string fname)

Then in your code you never pass that data ie:

Student student1 = new Student();

So either pass the firstname variable in when you are initialising or change your constructor in Student to allow it to accept nothing as well as a firstname as shown below:

class Student
{
    private string firstName;
    private string lastName;

    public Student(string fname = null)
    {
        this.FirstName = fname;
    }

this way you don't have to pass the data, but if you do it will be copied over to the firstname of the student object.

You could always change the null to something like "John" or "No Name" so that you have printable data in the object. just a suggestion though.

Regards, Slipoch

Slipoch
  • 750
  • 10
  • 23
0

Here is your code fixed up. There were 2 things:

  1. Your student class did not have a default constructor.
  2. Your student array list was not initialized in the course class.

Hope this helps.

using System;
using System.Collections;

class Program
{
    public static void Main(string[] args)
    {
        Student student1 = new Student();
        student1.FirstName = "a";
        student1.LastName = "w";

        Student student2 = new Student();
        student2.FirstName = "e";
        student2.LastName = "s";

        Student student3 = new Student();
        student3.FirstName = "i";
        student3.LastName = "o";

        Course c = new Course();

        ArrayList students = new ArrayList();

        c.students.Add(student1);
        c.students.Add(student2);
        c.students.Add(student3);

        foreach (Student o in c.students)
        {
            Student s = (Student)o;
            Console.WriteLine(s.FirstName);
        }
        Console.ReadLine();
    }
}

internal class Course
{
    public ArrayList students = new ArrayList();
}

internal class Student
{
    private string firstName;
    private string lastName;

    public Student()
    {

    }

    public Student(string fname)
    {
        this.FirstName = fname;
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
        }
    }

    public string LastName
    {
        get
        {
            return lastName;
        }

        set
        {
            lastName = value;
        }
    }
}
frostedcoder
  • 153
  • 7