Last active
September 4, 2015 17:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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