csharp / beginner
Snippet
Enforcing Input Requirements
Validation logic at the start of a method (Guard Clauses) prevents invalid data from causing errors or security vulnerabilities deeper in your code.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System;public class AccountManager {public void RegisterEmail(string email) {// Guard clause to ensure data security and integrityif (string.IsNullOrEmpty(email) || !email.Contains("@")) {throw new ArgumentException("Valid email is required.");}Console.WriteLine("Registered: " + email);}}
Breakdown
1
if (string.IsNullOrEmpty(email) || !email.Contains("@"))
Checks if the input is empty or lacks a mandatory character.
2
throw new ArgumentException("...");
Immediately stops execution and notifies the caller about the invalid input.