Skip to content

Instantly share code, notes, and snippets.

@kdarty
Last active September 4, 2015 17:48
Show Gist options
  • Save kdarty/bc393c5a70e5c11d2971 to your computer and use it in GitHub Desktop.
Save kdarty/bc393c5a70e5c11d2971 to your computer and use it in GitHub Desktop.
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.
/// <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;
}
}
List<string> recipients = new List<string>();
/*
recipients.Add("[email protected]");
recipients.Add("[email protected]");
*/
//recipients = null;
if (recipients.IsNullOrEmpty<string>())
{
MessageBox.Show("Empty List");
}
else
{
MessageBox.Show("We have a good Recipient List");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment