AnySafe
Determines if the collection contains any elements. If the argument is null, false will be returned. This is useful when you don't know in advance whether the collection will be null or not.
Source
public static bool AnySafe<T>(this IEnumerable<T> collection)
{
var result = false;
if (collection!= null)
{
result = collection.Any();
}
return result;
}
Short version:
public static bool AnySafe<T>(this IEnumerable<T> collection)
{
return (collection != null) ? collection.Any() : false;
}
Example
List<string> names = null;
var result = names.AnySafe(); //false, names is null
names = new List<string>();
result = names.AnySafe(); //false, no items in collection
names.Add("Item1");
result = names.AnySafe(); //true