In order to make sure that a list property would never return null, I declared it this way:
private IList<Item> _myList;
[NotNull]
public IList<Item> MyList
{
get { return _myList ?? new List<Item>(); }
set { _myList = value; }
}
This works, but I hate the syntax. Considering that I should use this technique extensively throughout my project, I'm looking for a better way to write this or a better solution to the same problem. Any idea?
That's the good way to do it but each time
MyList
is required and_myList
is null, you will create a new empty List... So if_myList
is empty and someone doMyList.Add(item);
it will not be added to the right list.Better do this :
That way, first time
_myList
is null, you create a new list. Then,_myList
will not be null.