csharp / beginner
Snippet
Preventing Invalid Data Input
Validating inputs is critical for security and stability. This check ensures that a string is not null, empty, or just whitespace before it is processed by the logic.
snippet.cs
csharp
1
2
3
4
5
6
7
public void RegisterUser(string username){if (string.IsNullOrWhiteSpace(username)){throw new System.ArgumentException("Username is required.");}}
Breakdown
1
if (string.IsNullOrWhiteSpace(username))
Checks if the string is null, empty, or consists only of whitespace.
2
throw new System.ArgumentException(...);
Triggers an error if the input does not meet the requirements.