Which do you prefer?
var foo = new Foo();
foo.Prop1 = "1";
foo.Prop2 = "2";
// etc...
this.Foos.Add(foo);
or
var foo = new Foo();
this.Foos.Add(foo);
foo.Prop1 = "1";
foo.Prop2 = "2";
// etc...
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.
Most of this is personal preference vs. concrete reasons but I prefer first because I find it to be the more straight forward approach. It follows the way I would think about this problem. It simply seems backwards to add it to the list and then initialize the value.
The one concrete reason I would prefer the first is it’s more resilient to changes in your code. For example if
Foowas later changed from a class to a struct it would break scenario #2 but not #1. This is a pretty far corner case though.In C# 3 and higher you could also simplify this by using a collection initializer.