0 day streak
csharp / intermediate
Snippet

Defensive Programming via Guard Clauses

Guard clauses at the beginning of a method prevent invalid data from flowing into your application logic, enhancing both security and stability.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public void UpdateProfile(string username, int age)
{
if (string.IsNullOrWhiteSpace(username))
throw new ArgumentException("Username cannot be empty.");
if (age < 18 || age > 120)
throw new ArgumentOutOfRangeException(nameof(age), "Invalid age range.");
// Proceed with secure update logic
}
Breakdown
1
if (string.IsNullOrWhiteSpace(username))
Checks for null, empty, or whitespace-only strings to ensure input integrity.
2
throw new ArgumentException(...)
Immediately halts execution with a descriptive error if validation fails.