How to check if a string is null or empty in C#

6 Answers

0 votes
using System;

class Program
{
    static void Main() {
        string str = null;
 
        if (string.IsNullOrEmpty(str) == true) {
            Console.WriteLine("Null Or Empty");
        }
        else {
            Console.WriteLine("Not Null Or Empty");
        }
    }
}




/*
run:

Null Or Empty

*/

 



answered Jan 2, 2017 by avibootz
edited Feb 12, 2024 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string str = "";
 
        if (string.IsNullOrEmpty(str) == true) {
            Console.WriteLine("Null Or Empty");
        }
        else {
            Console.WriteLine("Not Null Or Empty");
        }
    }
}




/*
run:

Null Or Empty

*/

 



answered Jan 2, 2017 by avibootz
edited Feb 12, 2024 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string str = "";
 
        if (str == null || str == "") {
            Console.WriteLine("Null Or Empty");
        }
        else {
            Console.WriteLine("Not Null Or Empty");
        }
    }
}




/*
run:

Null Or Empty

*/

 



answered Jan 2, 2017 by avibootz
edited Feb 12, 2024 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string str = null;
 
        if (str == null || str == "") {
            Console.WriteLine("Null Or Empty");
        }
        else {
            Console.WriteLine("Not Null Or Empty");
        }
    }
}




/*
run:

Null Or Empty

*/

 



answered Jan 2, 2017 by avibootz
edited Feb 12, 2024 by avibootz
0 votes
using System;
 
class Program
{
    static void Main()
    {
        string s1 = "c#"; 
        string s2 = "";  
        string s3 = null; 
   
        bool b1 = string.IsNullOrEmpty(s1); 
        bool b2 = string.IsNullOrEmpty(s2); 
        bool b3 = string.IsNullOrEmpty(s3); 
   
        Console.WriteLine(b1); 
        Console.WriteLine(b2); 
        Console.WriteLine(b3); 
    }
}
 
 
 
/*
run:
 
False
True
True
 
*/

 



answered Feb 12, 2024 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string s = null;
 
        try {
            if (s == null || s.Length == 0)
                Console.WriteLine("Null Or Empty");
            else
                Console.WriteLine("Not Null Or Empty");
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}


/*
run:

Null Or Empty

*/

 



answered Feb 12, 2024 by avibootz
...