Sunday, July 17, 2011

Extension for expression (List == null || List.Count > 0)

How many times in the time of coding you had to write an expression as:
List<T> list = new List<T>();
//...
if (list == null || list.Count  == 0)
{
// ...
}
I offering elegant and short solution with the assistance of extension with same name like string.You can use it not only in List but in everyone that inherits from IEnumarable<>:Add next extension(or class) to your project:
public static class Extensions
{
    public static bool IsNullOrDefault<T>(this IEnumerable<T> value)
    {
        return (value == null || value.Count() == default(int));
    }
}

Using:
List<string> list =  new List<string>();
bool isTrue = list.IsNullOrDefault();
list.Add("abc");
bool isFalse = list.IsNullOrDefault();

int[] numbers = null;
isTrue = numbers.IsNullOrDefault();
numbers = new int[] {1};
isFalse = numbers.IsNullOrDefault();

Enjoy!

No comments:

Post a Comment