ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

NotEmpty

Determines if the object is null or empty. string is evaluated with empty. Collections, Arrays and Dictionaries are evaluated for 0 items (items themselves may be null) All other objects are evaluated as null or not null.

Source

/// <summary>
/// Checks an object to see if it is null or empty.
/// <para>Empty is any collection, array or dictionary with an item count of 0 or a string that is empty.</para>
/// </summary>
public static bool NotEmpty(this object obj)
{
    if (obj != null && obj is ICollection)
        return ((ICollection)obj).Count > 0;
    if (obj != null && obj is IDictionary)
        return ((IDictionary)obj).Keys.Count > 0;
    if (obj != null && obj is Array)
        return ((Array)obj).Length > 0;
    return !(obj == null || string.IsNullOrEmpty(obj.ToString()));
}

Example

bool b = (new string[] {}).NotEmpty();
b = (new string[] {"", ""}).NotEmpty();
b = string.Empty.NotEmpty();
b = "".NotEmpty();
b = "123".NotEmpty();
b = (new List<string>()).NotEmpty();
b = (new Dictionary<string, string>()).NotEmpty();

// etc...

Author: Daniel Gidman

Submitted on: 13 dec. 2010

Language: C#

Type: System.Object

Views: 7397