While coding sometimes little tiny things are so frustrating , like forgetting to instantiate a List object before adding a new item, an easy solution will be to write an extension method like this
public static class ListExtension
{
public static void Add<T>(this List<T> list, T value, out List<T> newInstance)
{
if (list == null) list = new List<T>();
list?.Add(value);
newInstance = list;
}
}
and then use it like this
[Test]
public void SafeAddTest()
{
List<string> list = null;
list.Add("test",out list);
Assert.AreEqual(1,list.Count);
}
therefore whenever you want to make sure that the list that you are going to add to it is already instantiated you can simply pass the list instance as the second variable and that's it.
Happy coding :)