csharp / beginner
Snippet
Verifying Username Constraints
Security begins with validating user input. By checking for null values or insufficient lengths before processing data, you prevent common errors and potential exploits in your application logic.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System;public class AccountService {public void CreateUser(string name) {// Basic security check: ensure input is validif (string.IsNullOrWhiteSpace(name) || name.Length < 4) {throw new ArgumentException("Username is too short or empty.");}Console.WriteLine($"User {name} created successfully.");}}
Breakdown
1
string.IsNullOrWhiteSpace(name)
Checks if the string is null, empty, or consists only of spaces.
2
throw new ArgumentException(...)
Signals that a provided argument to the method is invalid.