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?