Console App Task 09: How to check is empty string[] folders in C# ?
To check if a string[] folders
array is empty or null, you can use the following approaches:
Method 1: Check for null
or Empty Length
if (folders == null || folders.Length == 0)
{
Console.WriteLine("The folders array is empty or null.");
}
✅ Best Practice: This checks if folders
is null
or has no elements.
Method 2: Check for Empty Strings Inside the Array
If you need to check whether the array contains only empty or whitespace strings, use LINQ:
using System;
using System.Linq;
if (folders == null || folders.All(string.IsNullOrWhiteSpace))
{
Console.WriteLine("The folders array is empty or contains only empty values.");
}
✅ Fix: string.IsNullOrWhiteSpace()
ensures that empty (""
) and whitespace (" "
) strings are also counted as empty.
Example Usage
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] folders = {}; // Empty array
if (folders == null || folders.Length == 0)
{
Console.WriteLine("folders array is empty or null.");
}
if (folders.All(string.IsNullOrWhiteSpace))
{
Console.WriteLine("folders array contains only empty or whitespace values.");
}
}
}
Conditions and checks:
Condition | Checks |
---|---|
folders == null |
If the array itself is null . |
folders.Length == 0 |
If the array has no elements. |
folders.All(string.IsNullOrWhiteSpace) |
If all elements are empty ("" ) or whitespace (" " ). |
If you like comment and share. 🚀
0 Comments