kdarty
9/4/2015 - 5:24 PM

Safely make sure that a List is not NULL or Empty in C#. The following Extension Method and corresponding sample code works well whether th

Safely make sure that a List is not NULL or Empty in C#.

The following Extension Method and corresponding sample code works well whether the List object has been initialized or not. The "!=null" ensures that the object is initialized and the ".Any()" makes sure that there are items in the List.

List<string> recipients = new List<string>();

/*
recipients.Add("joe@here.com");
recipients.Add("nobdy@here.com");
*/

//recipients = null;

if (recipients.IsNullOrEmpty<string>())
{
    MessageBox.Show("Empty List");
}
else
{
    MessageBox.Show("We have a good Recipient List");
}
/// <summary>
/// Extension Metion to verify that a Generic List is not NULL or Empty
/// </summary>
/// <typeparam name="T">List Type</typeparam>
/// <param name="source"><see cref="List"/> Source</param>
/// <returns><see cref="bool"/> (true/false)</returns>
public static bool IsNullOrEmpty<T>(this List<T> source)
{
    if (source != null && source.Any())
    {
        return false;
    }
    else
    {
        return true;
    }
}