This might be a stupid question, but is there any common practice for initializing collection properties for a user, so they don’t have to new up a new concrete collection before using it in a class?
Are any of these preferred over the other?
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's never used) get { if (myStrings == null) { myStrings = new List<string>(); } return myStrings; } set { myStrings = value; } } }
Option 4:
Any other good options for this?
In this case, I don’t see the reason for the lazy loading, so I would go with option 2. If you are creating a ton of these objects, then the number of allocations and GCs that result would be an issue, but that’s not something to consider really unless it proves to be a problem later.
Additionally, for things like this, I would typically not allow the assignment of the IList to the class. I would make this read-only. In not controlling the implementation of the IList, you open yourself up to unexpected implementations.