Add new item to list before initialization or after?

What 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... 
+4
source share
6 answers

These are mostly personal preferences over specific reasons, but I prefer first, because I think this is a more direct approach. This follows the way I think about this issue. It just seems the opposite to add it to the list and then initialize the value.

The only specific reason I would prefer the former is more resistant to changes in your code. For example, if Foo was later changed from class to structure, it would break script # 2, but not # 1. However, this is pretty far.

In C # 3 and above, you can also simplify this by using a collection initializer.

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

I like the first variation. It sounds logical and easier to follow.

0
source

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

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

I prefer the former simply because it seems to be clean to fully initialize the object before β€œmaking” it. In addition, before passing an object to a method that may have side effects for the object itself, it is best to make sure that you initialize it correctly to avoid any InvalidOperationExceptions . You never know if the Add method will expect foo.Prop1 to initialize.

0
source

When working with WinForm or ASP.Net, I would choose the first approach, although there was no difference in performance. I do this because it seems that I initialize everything and put the object in its place, instead of putting something there and changing it again and again. Just personal preference.

0
source

First, because:

  • it saves logical code (all property code settings, attributes and the general working on foo are closer to each other than code, where foo is considered as a unit in a wider context, which is the collection of all foos);

  • you never know if adding Foo to a collection foos can add a deep copy (rather than a shallow one), therefore, assuming that all these properties are set to an instance in the collection, I always set the properties before passing foo to any method that may or may not can create an alias for him

0
source

Source: https://habr.com/ru/post/1305708/


All Articles