C# Null and Empty Strings
In C#, a string can be null
, empty (""
), or consist of only whitespace. It's important to handle these cases to avoid exceptions.
Key Topics
1. Null vs. Empty Strings
A null
string means it has not been assigned a value, while an empty string is a string with zero characters.
Example: Null and Empty Strings
string nullString = null;
string emptyString = "";
Console.WriteLine(nullString == null); // Outputs: True
Console.WriteLine(emptyString == ""); // Outputs: True
2. Checking for Null or Empty Strings
Example: Using String.IsNullOrEmpty()
string input = null;
bool isNullOrEmpty = String.IsNullOrEmpty(input);
Console.WriteLine(isNullOrEmpty); // Outputs: True
3. Using String.IsNullOrWhiteSpace()
This method checks if a string is null
, empty, or consists only of whitespace characters.
Example: Checking for Whitespace Strings
string whitespaceString = " ";
bool isNullOrWhiteSpace = String.IsNullOrWhiteSpace(whitespaceString);
Console.WriteLine(isNullOrWhiteSpace); // Outputs: True
Key Takeaways
- A
null
string has not been assigned a value. - An empty string is a valid string with zero characters.
- Use
String.IsNullOrEmpty()
andString.IsNullOrWhiteSpace()
to safely check strings.