csharp / beginner
Snippet
Defensive String Handling Patterns
Defensive programming involves checking for nulls and trimming whitespace to ensure that user input doesn't break your application logic.
snippet.cs
csharp
1
2
3
4
5
6
string input = " user_data ";string sanitized = input?.Trim() ?? string.Empty;if (!string.IsNullOrEmpty(sanitized)) {// Safe to use sanitized}
Breakdown
1
input?.Trim()
The null-conditional operator ensures Trim() is only called if input is not null.
2
?? string.Empty
The null-coalescing operator provides a safe default value if the result is null.