Controllers and services use familiar control flow—if, loops, switch expressions, and early returns for validation failures. Guard clauses keep HTTP handlers readable.
Switch expressions (modern C#)
string RoleLabel(string role) => role switch {
"admin" => "Administrator",
"user" => "Standard user",
_ => "Guest"
};
Validation guard in a handler
if (string.IsNullOrWhiteSpace(email))
return BadRequest("Email required");
In MVC, return View(model) with errors; in APIs, return problem details or 400 responses.
Important interview questions and answers
- Q: switch vs if-else chains?
A: Switch expressions are concise for mapping discrete values; if-else for complex boolean logic. - Q: Early return benefits?
A: Reduces nesting in action methods—easier to read and test happy vs error paths.
Self-check
- When would you return early from an API action?
- What does
_mean in a switch expression?