开发者

Add new item to list before initializing or after?

开发者 https://www.devze.com 2022-12-25 21:08 出处:网络
Which do you prefer? var foo = new Foo(); foo.Prop1 = \"1\"; foo.Prop2 = \"2\"; // etc... this.Foos.Add(foo);

Which do you prefer?

var foo = new Foo();

foo.Prop1 = "1";
foo.Prop2 = "2";
// etc...

this.Foos.Add(foo);
开发者_如何学C

or

var foo = new Foo();
this.Foos.Add(foo);

foo.Prop1 = "1";
foo.Prop2 = "2";
// etc...


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 Foo was 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.

this.Foos.Add(new Foo() { Prop1="1"; Prop2="2" });


I like the first variation. It is logically sound and easier to follow.


I prefer the first simply because it seems cleaner to completely initialize the object before you are "done" with it. Also before you pass an object off to a method that may have side effects on the object itself it is best to ensure that you have properly initialized it in order to avoid any InvalidOperationExceptions. You never know if the Add method expects foo.Prop1 to be initialized.


In doing WinForm or ASP.Net, I would choose First approach, although no difference in terms of performance. I do this because it seems like I initialize everything and put the object to its place, rather than I put something there and alter it again and again. Just personal preference.


The first, because:

  • it keeps the code that is logically coupled closer (all the code setting properties, attributes, and overall working on foo closer together than the code where foo is treated as a unit in a larger context which is the collection of all foos);

  • you never know if adding a Foo to the collection of foos may add a deep copy (rather than a shallow reference) so, assuming the intent is to have all those properties set on the instance in the collection, I always set the properties before passing foo to any method that may or may not create an alias for it


I prefer to initialize properties with: (C# 3 or later)

this.Foos.Add(new Foo() { Prop1 = 1, Propr2 = 2 });


An old thread....

What about when you are searching for an item, creating a new item if not found, and changing it if found?

e.g.

var item=foos.FirstOrDefault(x=>x.Prop1=="1");
if (item==default)
{
   item=new Foo();
   foos.Add(item);
}

item.Prop2="2";
0

精彩评论

暂无评论...
验证码 换一张
取 消