Empty collection. Always.
This sucks:
if(myInstance.CollectionProperty != null)
{
foreach(var item in myInstance.CollectionProperty)
/* arrgh */
}
It is considered a best practice to NEVER return null
when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.
When talking about properties, always set your property once and forget it
public List<Foo> Foos {public get; private set;}
public Bar() { Foos = new List<Foo>(); }
In .NET 4.6.1, you can condense this quite a lot:
public List<Foo> Foos { get; } = new List<Foo>();
When talking about methods that return enumerables, you can easily return an empty enumerable instead of null
...
public IEnumerable<Foo> GetMyFoos()
{
return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}
Using Enumerable.Empty<T>()
can be seen as more efficient than returning, for example, a new empty collection or array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…