My favorite trick is using the null coalesce operator and parens to automagically instantiate collections for me.
private IList<Foo> _foo;
public IList<Foo> ListOfFoo
{ get { return _foo ?? (_foo = new List<Foo>()); } }
Please do not mistake this for the following
public IList<Foo> ListOfFoo
{ get { return _foo ?? new List<Foo>(); } }
My entry does the following:
- Checks _foo for null
- If null, assigns a new
List<Foo> to _foo
- Returns _foo
The second example does this:
- Checks _foo for null
- Returns a new
List<Foo> if _foo is null
In other words, in my implementation
Assert.AreSame(instance.Foo, instance.Foo)
returns true. In the second implementation, it returns FALSE.
Doing it the second way will result in the following bug:
instance.Foo.Clear();
instance.Foo.Add(new Foo());
var kaboom = instance.Foo[0] // ArgumentOutOfRangeException