0

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?

1
  • 2
    Use a loop, for(int i=0;i<candidates.Length;i++){candidates[i] = new Candidate();} Commented Nov 26, 2015 at 19:09

2 Answers 2

1

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

Comments

1

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.

1 Comment

Thanks, seems so obvious now haha

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.