views:

282

answers:

7

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?

A: 

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.

John Boker
+2  A: 

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.

Jimmy
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).
San Jacinto
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
@Alex you ought to know why not, haha. Let me hint a little bit: does your program work with an arbitrary-length file?
San Jacinto
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
Oops, meant to put a question mark on the end of my last comment. :)
Alex
@Alex it depends. Does the prof say he/she will ALWAYS give exactly 10? Can it be less than 10?
San Jacinto
Yes. the size can be less than ten.
Alex
@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.
San Jacinto
Thanks for your explanation and help. :)
Alex
@San#1: Thanks!
SLaks
+1  A: 

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();
}
SLaks
"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.
Jason
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)?
San Jacinto
Downvoters: See my edit.
SLaks
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?
San Jacinto
We do have an idea of the data type as he specified an object array.
Jason
@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.
San Jacinto
A: 

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);
}
Ian P
+1  A: 

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)) {
   ...
}
Guffa
appreciate the explanation.
Alex
+1  A: 

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

ccook
A: 

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
     }
 }
Cory Charlton
Why the down vote?
Cory Charlton