Initialization of the collection, so the user does not need to

This may be a dumb question, but is there a common practice for initializing collection properties for a user, so they don’t need to create a new specific collection before using it in the class?

Are any of them preferable over others?

Option 1:

public class StringHolderNotInitialized { // Force user to assign an object to MyStrings before using public IList<string> MyStrings { get; set; } } 

Option 2:

 public class StringHolderInitializedRightAway { // Initialize a default concrete object at construction private IList<string> myStrings = new List<string>(); public IList<string> MyStrings { get { return myStrings; } set { myStrings = value; } } } 

Option 3:

 public class StringHolderLazyInitialized { private IList<string> myStrings = null; public IList<string> MyStrings { // If user hasn't set a collection, create one now // (forces a null check each time, but doesn't create object if it never used) get { if (myStrings == null) { myStrings = new List<string>(); } return myStrings; } set { myStrings = value; } } } 

Option 4:

Any other good options for this?

+4
source share
3 answers

In this case, I see no reason for lazy loading, so I would go with option 2. If you create a ton of these objects, then the number of distributions and GC that will be the result will be a problem, but this is not what you need to consider if this there will be no problem later.

Also, for such things, I usually would not allow IList to be assigned to a class. I would do it read-only. By not controlling the implementation of IList, you open yourself up to unexpected implementations.

+10
source

For option 1: if you want to force the user to initialize something before using your class, then it is best to force it in the constructor.

For option 2: if you do not force the user, you really need to initialize the empty collection yourself in the constructor / initializer.

For option 3: lazy initialization makes sense only if it requires too much work or its slow / cumbersome operation.

My vote for option 2.

+2
source

The only real reason to use a lazy boot solution is optimization. And the first optimization rule is "do not optimize if you haven’t measured" :)

Based on this, I would go with the solution least likely to cause an error. In this case, this will be solution No. 2. Installing it in the initializer virtually eliminates the possibility of null ref here. The only way this will happen is if the user explicitly sets it to null.

+1
source

All Articles