0

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#.

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

And if I wanted to access one of the classes methods from the empArray would I just do empArray[i].SomeMethod?
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.
1

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.

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.