Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,244 questions

52,261 answers

573 users

How to check if a string is blank (empty, null, or contains only whitespace) in C#

1 Answer

0 votes
using System;

class IsBlankOrEmpty
{
    public static bool IsBlankOrEmptyMethod(string str) {
        // Check for null or empty string
        if (string.IsNullOrEmpty(str)) {
            return true;
        }

        // Check if the string contains only whitespace
        foreach (char ch in str) {
            if (!char.IsWhiteSpace(ch)) {
                return false; // Found a non-whitespace character
            }
        }
        return true;
    }

    static void Main()
    {
        string test1 = null;
        string test2 = "";
        string test3 = "   ";
        string test4 = "abc";

        Console.WriteLine("Test1: " + IsBlankOrEmptyMethod(test1));
        Console.WriteLine("Test2: " + IsBlankOrEmptyMethod(test2));
        Console.WriteLine("Test3: " + IsBlankOrEmptyMethod(test3));
        Console.WriteLine("Test4: " + IsBlankOrEmptyMethod(test4));
    }
}



/*
run:

Test1: True
Test2: True
Test3: True
Test4: False

*/

 



answered Jun 7, 2025 by avibootz
...