How do I initialize this array of custom types:
PostType[] q = new PostType[qArray.Length];
//initialize array
for( int x = 0; x < qArray.Length; x++)
q[x] = new PostType();
Is there a better way to initialize this array?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The way you are doing it is fine:
One thing I have changed are to rename the index veriable from x to i, as I find this easier to read, although it’s a subjective thing.
Another thing I have changed is the for loop end condition should depend on the length of q, not on the length of qArray. The reason for this is that with your method if you decide to change the first line to use a different length instead of qArray.Length, you’d have to remember to change the second line too. With the modified code you only need to update the first line of code and the rest will work without modification.
You could also do this using Linq:
But for large arrays this will be slower and not really easier to read in my opinion (especially if you haven’t seen it before). I think I’d probably just stick with the first method if I were you.