3

I need to validate if my string arrays are null or empty. Following is my code. Both don't work. Though the array is not initialized with any values, it shows as if it contains values. How can I fix it?

string abc[] = new string[3];

first code

if(abc != null)
{

}

second code

if(IsNullOrEmpty(abc))
{

}

public static bool IsNullOrEmpty<T>(T[] array)
{
    return array == null || array.Length == 0;
}
4
  • 2
    your array is neither null nor empty. so your code is working. Commented Jan 8, 2015 at 11:14
  • Though the array is not initialized with any values it shows as if it contains values where does it show that? Commented Jan 8, 2015 at 11:14
  • Did you try with bool IsNullOrEmpty(string[] array) { return array == null || array.Any(x => String.IsNullOrEmpty(x)); }. Array elements may be null or String.Empty (if this is what you want to check), array itself can be just null or 0 length (but not in your code). Feel free to replace .Any with .All (see MSDN). Commented Jan 8, 2015 at 11:14
  • 1
    -6 downvotes with 16k views... Commented May 17, 2020 at 14:29

1 Answer 1

23

This line:

string abc[] = new string[3];

creates a non-null, non-empty array (it is of size 3 and contains 3 null references).

So of course IsNullOrEmpty() is returning false.

Perhaps you want to also check if the array contains only null references? You could do so like this:

public static bool IsNullOrEmpty<T>(T[] array) where T: class
{
    if (array == null || array.Length == 0)
        return true;
    else
        return array.All(item => item == null);
}
Sign up to request clarification or add additional context in comments.

1 Comment

To turn this into an extension method, use IsNullOrEmpty<T>(this T[] array)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.