0

I have a homework assigment to iterate through an object array and print out these objects using for and foreach. I'm stuck on how to do that.

Questions

When you use a foreach loop, don't you have to declare the object? So the object declared in a foreach loop is null, because it doesn't call any constructors in my Employee class.

Code Snippet

    while ((worker = Employee.ReadFromFile(employeeDataReader)) != null)
    {
        employeeInfo[j] = worker;
        j++;
    }

    foreach (Employee person in employeeInfo)
    {
        person.Print(); 
    }

How do I print out the objects contained in an array? Am I 'doing it wrong'? Is there a better way?

8
  • 2
    Does that code not work? Do you get any errors? Commented Dec 10, 2009 at 1:02
  • 3
    Does ReadFromFile() return a new Employee object? Commented Dec 10, 2009 at 1:03
  • the foreach loop looks fine, my inclination would be to step into Employee.ReadFromFile and see what it is doing. Commented Dec 10, 2009 at 1:06
  • 3
    He's probably getting a NullReferenceException because the size of the array is larger than the number of employees in employeeDataReader. Commented Dec 10, 2009 at 1:09
  • 1
    How is your array declared? And how do you know how big to make it? Commented Dec 10, 2009 at 1:11

7 Answers 7

3

I'm a little confused. Perhaps you're also a little confused.

while ((worker = Employee.ReadFromFile(employeeDataReader)) != null)
{
    employeeInfo[j] = worker;
    j++;
}

this code (hopefully) creates a series of Employees. At some point in Employee.ReadFromFile, an Employee constructor is called. the constructed employee gets stuck in an array

foreach (Employee person in employeeInfo)
{
    person.Print(); // method that prints out information of each object of the employee class
}

in this code, person is only null if worker in the previous loop was null (which your boundary condition prevents). you don't need to call any more constructors, because you're just pulling out previously-contructed Employees from your array.


EDIT SLaks' answer is getting downvoted, so I'll just point out his comment to the question: the length of your array is probably greater than the number of Employee's you are reading in. This accounts for the nulls. Using List<Employee>, if that is an option, for employeeInfo would avoid this issue.

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

8 Comments

I think the downvotes (which I did not do) were intended for his original answer, not the edited one which is very worth up-voting (which I did).
ahh, thank you, my array is bigger than the file length! But we were supossed to make an array of size ten, and not use lists. Don't know why.
@Alex you ought to know why not, haha. Let me hint a little bit: does your program work with an arbitrary-length file?
oh, wow, thanks! but then why have us make a size ten array and not a size five array (which is the size of the file information)
@Alex well then, it's likely a exercise for you to make you consider general cases. In the spirit of "do it as an exercise," fire up your prog under the old system when it crashed. Run it in the debugger. You know what's breaking it now, so examine it. Learn how to use the debugger. It's the best friend you have, and Visual Studio has a world-class debugger.
|
1

A foreach loop like this:

foreach (Employee person in employeeInfo) {
   ...
}

works pretty much like a loop like this:

for (int i = 0; i < employeeInfo.Length; i++) {
   Employee person = employeeInfo[i];
   ...
}

So, the variable that you specify in the foreach loop gets it's values from each item in the array.

Note that the foreach loop iterates all items in the array. If you have declared a larger array than there are items in the file, you should only loop through the items that are populated:

for (int i = 0; i < j; i++) {
   Employee person = employeeInfo[i];
   ...
}

or:

foreach (Employee person in employeeInfo.Take(j)) {
   ...
}

Comments

1

It sounds like they want you to do a

for(int i=0;i<someArray.Length;i++)
    someArray[i].print();

and

foreach(SomeType item in someArray)
    item.print();

I suggest looking into the difference on your own :)

EDIT:

You might find this a good read:
http://www.csharp-station.com/Tutorials/lesson04.aspx

Comments

0

You should probably create an Employee ToString() method that prints out a string representation of the Employee, Then you can do something like Console.WriteLine(emp.ToString()); in your for loop.

Comments

0

I suspect that your problem is that the array isn't full, and that once your loop runs out of employees, it throws a NullReferenceException.

Instead of an array, you should use a List<T>. A List<T> will automatically resize when you call its Add method, so that it won't be too big or too small. In general, if you don't know exactly how many items you will have, you should always use a List<T> instead of an array.

For example:

List<Employee> employeeInfo = new List<Employee>();

while ((worker = Employee.ReadFromFile(employeeDataReader)) != null) {
    employeeInfo.Add(worker);
}

foreach (Employee person in employeeInfo) {
    person.Print(); // method that prints out information of each object of the employee class
}

Also, in your case, you don't need an array or a list; you could take it out completely and write the following:

while ((worker = Employee.ReadFromFile(employeeDataReader)) != null) {
    worker.Print();
}

5 Comments

"I have a homework assigment to iterate through an object array and print out these objects using for and foreach." A List<T> does not appear to be an option.
Why? From where did you glean this knowledge that the List is the more appropriate data type in his circumstance (especially considering this is homework)?
I didn't downvote, but that edit doesn't really make your original thesis any better... Why suggest a data type when you have no idea of the requirements?
We do have an idea of the data type as he specified an object array.
@Jason yes, I agree. We know he wants to use an array, he asks a question on iterators... so I don't know why the List<> suggestion came up as an answer originally. The new answer is much better.. think I will upvote.
0

Not sure I understand.

To iterate through a collection of objects, you have the basic concept down.

int[] integerArray = new integerArray[] {1, 2, 3, 4, 5};

foreach (int i in integerArray)
{
  Console.Writeline("{0} is the integer.", i);
}

Comments

0

I agree you should use the List<T> since it easily resizes dynamically.

You don't show it here but I assume you have something like

EmployeeInfo[] employeeInfo = new EmployeeInfo[10];

Up above. The problem is that if you only load 5 items in your ReadFromFile method then items 5-9 will be uninitialized.

You could also do:

foreach (Employee person in employeeInfo)
{
     if (person != null)
     {
         person.Print(); // method that prints out information of each object of the employee class
     }
 }

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.