C# shortcut for a List property that should never return null

1.9k views Asked by At

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?

3

There are 3 answers

4
Floc On BEST ANSWER

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 do MyList.Add(item); it will not be added to the right list.

Better do this :

private IList<Item> _myList;

[NotNull]
public IList<Item> MyList
{
    get { return _myList ?? (_myList = new List<Item>()); }
    set { _myList = value; }
}

That way, first time _myList is null, you create a new list. Then, _myList will not be null.

1
CDove On

As of C# 6.0, you can initialize properties that use an auto-implemented field. This will ensure that MyList is never a null value:

public IList<Item> MyList { get; set; } = new List<Item>();
0
Patrick Hofman On

This works, but I hate the syntax.

I hate the idea that returning a new list and immediately dropping it is a good idea. I think you should try to think of other ways to solve this.

Does the returned value really be non-nullable? If so, create a proper instance instead of dropping it the moment you create it:

[NotNull]
public IList<Item> MyList
{
    get { return _myList ?? (_myList = new List<Item>()); }
    set { _myList = value; }
}

If you can life with a nullable list, you might just want to shorthand null-checking:

if (list?.Contains(...) ?? false)
{ }