views:

213

answers:

2

So I've been trying to figure out how to populate an array with an object I have created in C#. I found this code sample which explains a bit about what I need to do.

for (int i = 0;i<empArray.Length;i++)
       {
           empArray[i] = new Employee(i+5);
       }

But what happens if I pass more than one parameter into my constructor? Will this look any different? Like empArray[i] = new Employee(i, j, k); and so on. And if so how will read these objects out of the array, to say the Console. Would

Console.WriteLine(empArray[i])

do the trick if the object has more than one variable passed into it, or will I need a multi dimensional array? I apologize for all the questions, just a little new to C#.

+1  A: 

Yes, this would work. In the statement array[i] the i is used as a reference to a position in a array, and has nothing to do with the actual contents of the object.

Andrew
+2  A: 

The parameters passed in to the constructor are simply information for the object to initialize itself. No matter how many parameters you pass in, only a single Employee object will come out, and that object will be put in empArray[i].

You will always access the Employee objects using empArray[<index>] where index is an integer where 0 <= index < empArray.Length.

Console.WriteLine takes a string or any object with a ToString() method on it. So if the Employee object implements ToString(), then Console.WriteLine(empArray[i]) will work. You might implement ToString() like this:

public string ToString()
{
    return String.Format("{0} {1}", this.FirstName, this.LastName);
}
Aaron
And if I wanted to access one of the classes methods from the empArray would I just do empArray[i].SomeMethod?
LeSabo
That is exactly right! `empArray[i]` returns the object at index `i`, so you can treat it as though you were dealing directly with that object.
Aaron
Right on, I appreciate your help thanks a lot!
LeSabo