Adam
Adam

Reputation: 61

Creating an array of objects from a class in C#

I am trying to create an array of 20 candidates from my Candidate class. So far, this is what I have:

Candidate candidate0 = new Candidate();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
...
Candidate candidate19 = new Candidate(); 

Candidate[] candidates = new Candidate[20];
candidates[0] = candidate0;
candidates[1] = candidate1;
candidates[2] = candidate2;
candidates[3] = candidate3;
...
candidates[19] = candidate19;

I know this is not the correct or 'best' way to do this. What would be the best way?

Upvotes: 0

Views: 103

Answers (2)

jim tollan
jim tollan

Reputation: 22485

Adam - you'd be subjectively better off using a list for this along the lines of:

List<Candidate> canditateList = new List<Candidate>();

// MaxLength is a const defined somewhere earlier perhaps
for(int i=0 ;i<MaxLength;i++){
  canditateList.Add(new Candidate(){... properties here});
}

// etc, etc.

You could then factor this out to an array if required using:

var candidateArray = canditateList.ToArray();

Just my initial thoughts, tho you may of course have a good reason for wishing to use an array from the start, my premise is that I would go with a list and party on that for various extracted flavours.

Upvotes: 1

Perfect28
Perfect28

Reputation: 11327

What you need is a for loop :

int candidateLength = 20 ; 

Candidate[] candidates = new Candidate[candidateLength ];

for(int i=0 ; i<candidates.Length ; i++)
{
   candidates[i] = new Candidate();
}

Upvotes: 1

Related Questions