Search code examples
c#listnullshorthand

Shorthand for add object to list if object is not null


Say I have the following in c#:

List<Foo> fooList = new();
Foo fooObject;

Does a shorthand exist for the following?

if(fooObject != null)
{
    fooList.Add(fooObject);
}

Depending on the situation in my code, fooObject might be null or not, but I would like to add it to the fooList if not null.

As far as my research goes, none of the null-coalecsing or ternary operator possibilities cover the one above.


Solution

  • The only solution I can think of is using an extension method

    public class Foo 
    {
    }
    static class Program
    {
        static void Main(string[] args)
        {
            List<Foo> list =  new List<Foo>();
            Foo item = null;
            list.AddNotNull(item);
            item = new Foo();
            list.AddNotNull(item);
        }
    
        public static void AddNotNull<T>(this IList<T> list, T item) where T : class
        {
            if (item != null)
            {
                list.Add(item);
            }
        }
    }