Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. If Else Statement

If Else Statement

Date- Dec 09,2023 Updated Feb 2026 3500
csharp if else statement

What is an If-Else Statement?

In C#, the if-else statement is a conditional control structure that enables the execution of specific code blocks based on whether a given condition evaluates to true or false. This allows developers to implement branching logic in their programs, making it possible to handle various scenarios and outcomes effectively. The if-else structure is particularly useful in situations where decisions need to be made based on user input, system states, or other dynamic conditions.

The if part of the statement executes when the condition is true, while the else part executes when the condition is false. This flexibility allows for a clear and organized approach to code execution, enhancing readability and maintainability.

Syntax of If-Else Statement

The syntax of an if-else statement in C# is straightforward. Below is the general structure:

if (condition) {
    // block of code to be executed if the condition is True
} else {
    // block of code to be executed if the condition is False
}

In this structure, the condition is a Boolean expression that evaluates to either true or false. Depending on the result, the corresponding code block will be executed.

Example of If-Else Statement

Let’s take a look at a simple example to illustrate the usage of the if-else statement:

using System;

public class Program {
    public static void Main() {
        int age = 19;
        if (age < 18) {
            Console.WriteLine("Your age is less than 18");
        } else {
            Console.WriteLine("Your age is 18 or older.");
        }
    }
}

In this example, the program checks if the age variable is less than 18. If it is, it prints a message indicating that the user is underage. Otherwise, it states that the user is 18 or older. The output will be: Your age is 18 or older.

Chaining If-Else Statements

In many scenarios, a single condition is not enough to capture all the necessary logic. C# provides the ability to chain multiple if-else statements to handle various conditions. This is done using else if clauses.

using System;

public class Program {
    public static void Main() {
        int score = 85;
        if (score >= 90) {
            Console.WriteLine("Grade: A");
        } else if (score >= 80) {
            Console.WriteLine("Grade: B");
        } else if (score >= 70) {
            Console.WriteLine("Grade: C");
        } else {
            Console.WriteLine("Grade: D");
        }
    }
}

In this example, the program evaluates the score and assigns a grade based on the defined ranges. This approach allows for clear and organized handling of multiple conditions.

Nested If-Else Statements

Another powerful feature of the if-else statement is the ability to nest them within one another. This means you can have an if-else statement inside another if or else block, allowing for more complex decision-making.

using System;

public class Program {
    public static void Main() {
        int age = 20;
        bool hasPermission = true;

        if (age >= 18) {
            if (hasPermission) {
                Console.WriteLine("Access granted.");
            } else {
                Console.WriteLine("Access denied: Permission required.");
            }
        } else {
            Console.WriteLine("Access denied: You must be 18 or older.");
        }
    }
}

This example demonstrates how you can check for multiple conditions by nesting if-else statements. The outer if checks the age, while the inner if checks for permission.

Edge Cases & Gotchas

When working with if-else statements, it’s essential to be aware of certain edge cases and potential pitfalls:

  • Boolean Expressions: Ensure that the condition is a valid Boolean expression. Avoid using assignments in the condition, as this can lead to unintended behavior.
  • Floating Point Comparisons: Be cautious when comparing floating-point numbers due to precision issues. Consider using a tolerance level for comparisons.
  • Short-Circuiting: Be aware of how logical operators like && (AND) and || (OR) short-circuit. The second condition may not be evaluated if the first condition determines the outcome.

Performance & Best Practices

While if-else statements are efficient for decision-making, there are best practices to keep in mind:

  • Keep Conditions Simple: Aim for clarity in your conditions. Complex expressions can make code harder to read and maintain.
  • Use Switch Statements: For multiple discrete values, consider using a switch statement instead of multiple if-else statements for better readability.
  • Avoid Deep Nesting: Excessive nesting can lead to complicated code. Instead, try to flatten your logic where possible.

Conclusion

The if-else statement is a vital component of C# programming that allows for effective decision-making in applications. By mastering its usage, developers can write more dynamic and responsive code.

Key Takeaways:

  • The if-else statement executes different code blocks based on the evaluation of a condition.
  • Chaining and nesting if-else statements enables handling of complex decision-making scenarios.
  • Be mindful of edge cases, such as Boolean expressions and floating-point comparisons.
  • Follow best practices to ensure code clarity and maintainability.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Introduction to C# Programming: Your First Steps in Software Development
Mar 08, 2026
Break and Continue Statements Explained in Python with Examples
Dec 09, 2023
Mastering While Loops in C#: A Complete Guide with Examples
Dec 09, 2023
Understanding Variables in Python: A Complete Guide with Examples
Dec 09, 2023
Previous in C#
Mastering the foreach Loop in C#: A Complete Guide with Examples
Next in C#
Complete Guide to Lists in C#: Examples and Best Practices
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11510 views
  • The report definition is not valid or is not supported by th… 10880 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9871 views
  • Get IP address using c# 8700 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor