No more NullReferenceException for Lists in C#

Ali Alp - Jun 7 '19 - - Dev Community

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

and then use it like this

[Test]
public void SafeAddTest()
{
    List<string> list = null;
    list.Add("test",out list);

    Assert.AreEqual(1,list.Count);
}
Enter fullscreen mode Exit fullscreen mode

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 :)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player