Best examples of C# conditional statements: examples & explanations
Before talking theory, let’s start with real examples. In production C# code, conditional statements show up in places like:
- Validating API request payloads.
- Enforcing authentication and authorization.
- Toggling features with configuration flags.
- Handling different behaviors based on environment (Development vs Production).
- Branching logic in game loops or real-time simulations.
All of these rely on some flavor of if, else if, else, or switch. The best examples of C# conditional statements are the ones that are readable six months later, not just the ones that compile today.
Classic if and else – simple, readable, still the workhorse
Let’s start with a straightforward example of C# conditional statements using if / else. This is the pattern you see everywhere, from console apps to ASP.NET APIs.
public string GetDiscountCategory(int age)
{
if (age < 0)
{
throw new ArgumentOutOfRangeException(nameof(age));
}
if (age < 13)
{
return "Child";
}
else if (age < 65)
{
return "Adult";
}
else
{
return "Senior";
}
}
This small function shows several examples of C# conditional statements working together:
- A guard clause (
if (age < 0)) to reject invalid data early. - A chain of
if/else if/elseto categorize a value.
In real codebases, this style often appears in validation layers or pricing logic. It’s boring, and that’s exactly why it’s good.
Input validation: examples of C# conditional statements in APIs
Here’s a more practical example of C# conditional statements: examples & explanations that reflect what you’d actually write in an ASP.NET Core API controller.
[HttpPost("/orders")]
public IActionResult CreateOrder([FromBody] CreateOrderRequest request)
{
if (request == null)
{
return BadRequest("Request body is required.");
}
if (string.IsNullOrWhiteSpace(request.CustomerId))
{
return BadRequest("CustomerId is required.");
}
if (request.Items == null || request.Items.Count == 0)
{
return BadRequest("At least one item is required.");
}
if (request.TotalAmount <= 0)
{
return BadRequest("TotalAmount must be positive.");
}
// Happy path continues here...
return Created("/orders/123", new { id = 123 });
}
These are the kind of real examples of C# conditional statements that keep your API from accepting garbage. The pattern is simple: fail fast with clear error messages. This style is common in modern backend services and aligns with validation guidance you’ll see in many enterprise coding standards.
For broader discussion on input validation and error handling patterns (language-agnostic, but still relevant), the NIST Secure Software Development Framework from NIST.gov is a solid reference.
Feature flags and configuration: conditional logic from config
Modern apps often change behavior based on configuration or environment, not hardcoded values. Here’s an example of C# conditional statements wired to configuration flags.
public class RecommendationsService
{
private readonly bool _useNewAlgorithm;
public RecommendationsService(IConfiguration config)
{
_useNewAlgorithm = config.GetValue<bool>("Features:UseNewRecommendations");
}
public IEnumerable<Product> GetRecommendations(User user)
{
if (_useNewAlgorithm)
{
return GetRecommendationsV2(user);
}
else
{
return GetRecommendationsV1(user);
}
}
}
Here, the conditional is tied to a feature flag. Examples include A/B testing new algorithms, turning off expensive features in low-resource environments, or gradually rolling out changes. In production systems, this pattern often connects to configuration providers like Azure App Configuration or LaunchDarkly, but the underlying C# conditional statements look very much like this.
switch statements: cleaner branching for discrete values
When you’re branching on a single value with several options, a switch is usually more readable than a long if chain. Here’s a classic example of C# conditional statements using switch for HTTP status mapping.
public static string GetStatusMessage(int statusCode)
{
switch (statusCode)
{
case 200:
return "OK";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 404:
return "Not Found";
case 500:
return "Server Error";
default:
return "Unknown Status";
}
}
In real services, examples include mapping enums to user-facing labels, routing commands based on type, or choosing different serializers. Compared to stacked if statements, this style is easier to scan and maintain.
If you’re dealing with HTTP concepts more broadly and want standardized meanings for these codes, the MDN Web Docs HTTP status reference is one of the best curated resources.
Modern C# pattern matching: the best examples for expressive logic
Since C# 8 and beyond, pattern matching has quietly become one of the best examples of C# conditional statements done right. Instead of a maze of if conditions, you can express intent more directly.
switch expressions with pattern matching
public static decimal CalculateShipping(decimal orderTotal, string countryCode)
{
return (orderTotal, countryCode) switch
{
(<= 0, _) => throw new ArgumentOutOfRangeException(nameof(orderTotal)),
(< 50m, "US") => 5.99m,
(< 50m, _) => 15.99m,
(>= 50m and < 100m, "US") => 2.99m,
(>= 100m, "US") => 0m,
(>= 50m, _) => 9.99m,
_ => 19.99m
};
}
This single expression replaces a long series of nested if statements. It’s one of the clearest examples of C# conditional statements where pattern matching dramatically improves readability:
- Multiple inputs (
orderTotal,countryCode) are handled together. - Conditions read almost like business rules.
- The final
_pattern is a clear catch-all.
Type patterns with is
You’ll also see pattern matching used for type checks, especially in event handling or message processing.
public void HandleEvent(object evt)
{
if (evt is UserRegistered registered)
{
SendWelcomeEmail(registered.Email);
}
else if (evt is OrderPlaced placed)
{
ReserveInventory(placed.OrderId);
}
else if (evt is PaymentFailed failed)
{
NotifyBillingTeam(failed.PaymentId);
}
}
Here, each if is both a type check and a cast. These are real examples of C# conditional statements that show up in event-driven architectures and message buses.
Guard clauses vs nested if blocks
A common style question: should you nest if statements or bail out early? In 2024, most C# teams favor guard clauses to avoid the “arrow code” problem (code that keeps indenting to the right).
public User GetActiveUser(string userId)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new ArgumentException("userId is required", nameof(userId));
}
var user = _userRepository.FindById(userId);
if (user == null)
{
throw new InvalidOperationException("User not found");
}
if (!user.IsActive)
{
throw new InvalidOperationException("User is inactive");
}
return user;
}
Compare that to a deeply nested version and you’ll see why these examples of C# conditional statements are considered more maintainable. Each condition exits early, and the happy path stays at the left margin.
For general guidance on code clarity and maintainability (across languages), the principles in MIT’s 6.005 Software Construction materials are still widely referenced in academia and industry.
Ternary operator ?: – concise, but easy to abuse
The conditional (ternary) operator is one of the shortest examples of C# conditional statements. It’s perfect for simple, expression-level decisions.
public string GetTemperatureLabel(double tempFahrenheit)
{
return tempFahrenheit >= 100.4
? "Fever"
: "Normal";
}
This is readable, and it’s a good example of C# conditional statements used for quick decisions like label selection or formatting. Where people get into trouble is stacking ternaries:
// Hard to read – avoid this
string risk = score > 80 ? "High" : score > 50 ? "Medium" : "Low";
If you find yourself nesting ternaries, it’s usually time to move to a switch expression or a small function with ordinary if statements.
Real examples of C# conditional statements in async and I/O code
Conditional logic in asynchronous code looks familiar, but you need to be careful about race conditions and partial failures. Here’s a realistic example of C# conditional statements in an async method that calls an external API.
public async Task<UserProfile?> GetProfileOrNullAsync(string userId, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(userId))
{
return null;
}
var response = await _httpClient.GetAsync($"/profiles/{userId}", ct);
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null; // Profile doesn’t exist
}
// For other failures, bubble up
response.EnsureSuccessStatusCode();
}
var json = await response.Content.ReadAsStringAsync(ct);
return JsonSerializer.Deserialize<UserProfile>(json);
}
These examples include layered conditional checks:
- Input validation before making a network call.
- HTTP status handling with a nested
if. - A mix of graceful handling (
404) and strict handling (EnsureSuccessStatusCode).
In distributed systems, this style of C# conditional statements is everywhere: retry logic, fallback to cache, and circuit breakers all rely on nuanced branching.
Data-driven conditionals: when logic moves into data
As systems grow, you often move from hardcoded if statements to data-driven rules. But the underlying C# conditional statements are still doing the work.
public class TaxRule
{
public string State { get; init; } = string.Empty;
public decimal MinAmount { get; init; }
public decimal MaxAmount { get; init; }
public decimal Rate { get; init; }
}
public decimal CalculateTax(decimal orderTotal, string state, IEnumerable<TaxRule> rules)
{
foreach (var rule in rules)
{
if (rule.State == state &&
orderTotal >= rule.MinAmount &&
orderTotal < rule.MaxAmount)
{
return orderTotal * rule.Rate;
}
}
return 0m;
}
This is a subtle but important example of C# conditional statements: examples include pricing rules, access control lists, and routing tables. Instead of hardcoding every rule, you load them from a database or configuration, but your if logic still decides which rule applies.
Putting it together: picking the right conditional style
By now we’ve walked through multiple real examples of C# conditional statements: examples & explanations that range from simple if blocks to pattern matching and data-driven rules. The interesting question isn’t “which is fastest?” (for most business code, they’re all fast enough). The question is: which one makes the intent obvious?
A few practical guidelines:
- Use
if/elsefor straightforward, linear checks and guard clauses. - Use
switchorswitchexpressions when branching on a single value or a small tuple. - Use pattern matching when you have multiple conditions that naturally read as rules.
- Use ternary
?:only for short, expression-level decisions. - Prefer guard clauses over deep nesting to keep code readable.
These patterns line up with what you’ll see in modern C# codebases, open-source projects, and coding guidelines used in large organizations.
FAQ: examples of C# conditional statements, syntax, and gotchas
Q: Can you show another short example of C# conditional statements checking multiple conditions?
Yes. Here’s a concise login check that combines logical operators:
public bool CanUserAccess(bool isAuthenticated, bool isLockedOut, bool hasRequiredRole)
{
if (!isAuthenticated || isLockedOut)
{
return false;
}
return hasRequiredRole;
}
These examples include both negative checks (!isAuthenticated) and a final positive condition. This mirrors real authentication flows in web apps.
Q: What is an example of using switch vs if for enums?
public enum SubscriptionPlan
{
Free,
Pro,
Enterprise
}
public bool HasPrioritySupport(SubscriptionPlan plan)
{
return plan switch
{
SubscriptionPlan.Enterprise => true,
SubscriptionPlan.Pro => true,
_ => false
};
}
This example of C# conditional statements with a switch expression is more compact and easier to extend than a chain of if (plan == ...) checks.
Q: Are nested if statements always bad?
No. Sometimes nested if statements are the clearest way to express “only check this if the previous condition passed.” Overusing them leads to unreadable code, but targeted nesting—especially when each level has a clear meaning—is fine. The best examples of C# conditional statements balance flat structure with clear grouping.
Q: How do conditionals interact with nullable reference types in modern C#?
With nullable reference types enabled, you’ll often see explicit null checks:
public string GetDisplayName(User? user)
{
if (user is null)
{
return "Guest";
}
return string.IsNullOrWhiteSpace(user.DisplayName)
? user.Email
: user.DisplayName;
}
These examples of C# conditional statements work hand in hand with the compiler’s nullability analysis to reduce runtime NullReferenceExceptions.
Q: Where can I learn more patterns beyond basic conditionals?
For deeper design patterns that influence how you structure conditional logic (strategy, state, specification), university materials like the Carnegie Mellon Software Engineering Institute and courses from major CS programs (for example, Stanford and MIT) offer freely available lectures and notes. While not specific to C#, the ideas translate directly, and the examples of conditional logic are easy to adapt into C# syntax.
Related Topics
Practical examples of polymorphism in C++: function overloading
Best examples of dynamic memory allocation in C++: new and delete
Practical examples of C# variable declaration and initialization examples
Modern examples of C++ operator overloading: custom operators examples that actually matter
Best examples of C# conditional statements: examples & explanations
Real‑world examples of C# exception handling: 3 practical patterns every developer should know
Explore More C++ Code Snippets
Discover more examples and insights in this category.
View All C++ Code Snippets