0 day streak
csharp / beginner
Snippet

Guard Clauses for State Integrity

Using guard clauses at the beginning of a function helps prevent bugs by ensuring inputs are valid before any logic is executed.

snippet.cs
csharp
1
2
3
4
5
6
public void UpdateAge(int newAge) {
if (newAge < 0 || newAge > 120) {
throw new System.ArgumentException("Age out of valid range.");
}
// Proceed with logic
}
Breakdown
1
if (newAge < 0 || newAge > 120)
Checks if the input violates the business rules early.
2
throw new ...
Halts execution immediately if the validation fails, protecting the rest of the code.