csharp / beginner
Snippet
Null-Safe Input Validation
Checking for null or whitespace prevents security vulnerabilities and crashes caused by unexpected empty user input.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;public class Program {public static void RegisterUser(string username) {if (string.IsNullOrWhiteSpace(username)) {throw new ArgumentException("Username cannot be empty or whitespace.");}Console.WriteLine($"User {username} registered.");}public static void Main() {RegisterUser("Alex");}}
Breakdown
1
string.IsNullOrWhiteSpace(username)
Returns true if the string is null, empty, or consists only of white-space characters.
2
throw new ArgumentException(...)
Halts execution and notifies the caller that the input was invalid.