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#.
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
Employeeobject will come out, and that object will be put inempArray[i].You will always access the
Employeeobjects usingempArray[<index>]where index is an integer where 0 <= index < empArray.Length.Console.WriteLinetakes a string or any object with aToString()method on it. So if theEmployeeobject implementsToString(), thenConsole.WriteLine(empArray[i])will work. You might implementToString()like this: