DEV Community

Discussion on: No more NullReferenceException for Lists in C#

Collapse
 
kbiel profile image
Ken in NH

This is a confusing use of "out". Not that I recommend it, but a better way of handling this case is to return the incoming list or new list. This would allow functional code at least. It still would not be obvious that you must replace your list reference with the reference emerging from the method.

If you find that you often forget to instantiate, use "var". In your unit test, it would stop you from getting an "NullReferenceException" as well.

[Test]
public void SafeAddTest()
{
    //var list = null; //This won't even compile!
    var list = new List<string>(); //You are forced to provide type
                                   //through an instance for "var".
    list.Add("test");

    Assert.AreEqual(1,list.Count);
}