How to check if a string is null or empty in C#?
- User
How to check if a string is null or empty in C#?
Assistant
You can check if a string is null or empty in C# using:
- string.IsNullOrEmpty(string)
For example:
string str = null; string str2 = ""; string str3 = "Hello"; string.IsNullOrEmpty(str); // Returns true string.IsNullOrEmpty(str2); // Returns true string.IsNullOrEmpty(str3); // Returns falseThis will return true if the string is null, empty, or contains only whitespace.
You can also check for null and empty separately with:
- string == null
- string.Length == 0
For example:
string str = null; string str2 = ""; string str3 = " "; // Contains only whitespace string str4 = "Hello"; str == null; // Returns true str2.Length == 0; // Returns true str3.Length == 0; // Returns false str4.Length == 0; // Returns falseSo in summary, you can check for null/empty strings in C# with:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.