Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
how to check string array is Null or Empty?
Posted

C#
if (myArray == null)
   System.Console.WriteLine("array is not initialized");
else if (myArray.Length < 1)
   System.Console.WriteLine("array is empty");


Something like that.

—SA
 
Share this answer
 
Comments
Wendelius 6-Aug-11 4:48am    
You have a faster keyboard :) my 5
Sergey Alexandrovich Kryukov 6-Aug-11 15:15pm    
Thank you, Mika.
--SA
might helps,

C#
static void Main(string[] args)
{
    string[] myStringArray = null;
    if (IsNullOrEmpty(myStringArray))
        Console.WriteLine("Null or Empty");
}

static bool IsNullOrEmpty(string[] myStringArray)
{
    return myStringArray == null || myStringArray.Length < 1;
}


also, you can make IsNullOrEmpty as a extension method :)
 
Share this answer
 
If you're using an array, you can check it's length[^]

On the other hand if you're using simply a string, you can check IsNullOrEmpty[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Aug-11 15:13pm    
You did not mention comparison array with null. Also, you should understand that string is not an array of character or whatever, it is not an array at all. It is immutable and implementing value semantics, also, it uses intern pool, which is not trivial thing.


OP asks about array of string and nothing about its content. Strings can be anything.

I voted 4 anyway.

See my solution here http://www.codeproject.com/Answers/237095/how-to-compare-two-strings-in-csharp#answer5.

--SA
Wendelius 6-Aug-11 16:11pm    
You're right about the array and I did forget about the null check.

I wanted to add the null/empty string test even though the OP asked about the array because the way the question was formulated made me wonder if he's using string type instead of an array (referral to empty).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900