Reputation: 452
Is it good to initialise collection properties?
for example, my class is,
public class Part
{
public int Id { get; set; }
public int PartTypeId { get; set; }
public IList<Child> Instructions { get; set; }
}
Is it a good idea to initialise Instructions like this?:
public IList<Child> Instructions { get; set; } = new List<Child>();
Upvotes: 4
Views: 1407
Reputation: 724142
Well, if you don't initialize your collections, you won't be able to use them. If you're going to use a collection, might as well initialize it ASAP so you can just use it without worrying about a null reference.
Lazily initializing an empty collection isn't necessary. An empty collection doesn't take much work to initialize and doesn't take up much memory once initialized. Even if you don't end up populating it during the lifetime of your application, it's not going to have a measurable impact on performance.
A non-empty collection is somewhat of a different story. If it's a small collection of primitive values, it probably isn't going to make much of a difference either. But if this will be a collection of large, complex objects that isn't required on launch, it may be wise to do it lazily. Whether you do that with a new
in the property declaration and populating it separately, or new
ing and populating it all at once on demand, is a matter of preference (and whether your application relies on the collection being there or not — most applications ask if the collection is populated or not instead, which brings us back to my point on empty collections).
As pointed out by Damien_The_Unbeliever, you probably don't want your collection property to be settable by anyone other than the class itself, if at all. All your collection operations will be performed on the collection itself without actually changing (or removing) the collection, so a setter is not required and should in fact be left out:
public IList<Child> Instructions { get; } = new List<Child>();
Upvotes: 8