search

C# if Statement

Sep 03, 2024 pm 03:09 PM
c#c# tutorial

  • C# is a very powerful object-oriented programming language of.Net Framework. The .Net framework is an extensive, revolutionary platform using which the following applications, such as Windows applications, Web applications, Web Services, etc., can be easily developed.
  • There are multiple languages supported by this framework, such as C#, C++, Visual Basic, etc. Therefore, the applications developed using this framework are supported by multiple platforms. For example, C# is one of the very popular languages of this framework.
  • C# is simple yet very powerful. It was created by Microsoft, and using it, we can create different types of applications based on our requirements, such as web applications, console applications, windows applications.

Let us understand the basic structure of the C# program before we jump to the if statement.

To print C# if Statement as output.

using System;   //declaring namespace
class Example1   //declaring class
{
static void Main(string[] args) {     //declaring class method
Console.WriteLine("C# IF STATEMENT");    //print
}
}

Output:

C# if Statement

This article basically focuses on the C# IF statement, so let us get on with it step by step.

The “if” Statement in C#

  • Several decision-making statements are available in C# where certain logical conditions are required to flow a program continuously. The decision-making statements included in C# are – if statement, if-else statement, switch statement, and ternary operator.
  • The “if” condition or the if-else condition takes up a boolean expression as its parameter and evaluates it. Only if the condition being evaluated is true, the block of a statement under if the statement is executed. In case the condition is false, the if block will be skipped.

C# if Statement in detail

The conditional if statement accepts a boolean expression or a condition inside brackets or as a parameter which is followed by a single line or multi-line block of code. During the runtime, when the program has been executed, the condition inside the brackets is evaluated. If this boolean expression results in true, then the code block following the if statement will be executed.

Consider the following example where the if condition contains true as an expression.

The syntax of the if the statement is –

if(a conditional statement or boolean expression)
{
// the block of code to be executed if the expression results into true
}

Let us understand this further with an example.

Consider –

using System;
class Ex2
{
static void Main(string[] args)
{
{
if(true)
Console.WriteLine("True Condition: We are inside the for loop");
if(false)
Console.WriteLine("False Condition: We will not be able to enter inside the for loop");
}
}
}
  • As explained above, if the statement contains a condition, that would result in true or false. The execution of the code associated with the if loop depends on this boolean expression. Consider the example with the problem statement given below for further clarification –
  • Problem Statement: Ravi’s age (R_age) is 15 years. Amar’s age(A_age) is 12 years. Print if Ravi is elder or younger or equal to Amar.

For Example –

using System;
class Ex3
{
static void Main(string[] args)
{
int R_age = 15, A_age = 12;
if ( R_age > A_age)
Console.WriteLine("Ravi is elder to Amar");
if (R_age 
<p><strong>Output</strong> –</p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534736646938.png?x-oss-process=image/resize,p_40" class="lazy" alt="C# if Statement" ></p>
<p>Note that the boolean expression in the first ‘if’ statement is given as a parameter evaluates to be true as Ravi’s age(15) is greater than Amar’s age(12). As only one if statement holds true, only the first block will be executed associated with the first if condition.</p>


<h3 id="if-else-Statement">if-else Statement</h3>
<p>The second type of conditional statement provided by C# is the if-else statement. The second part of the code, which needs to execute if the condition holds false, can be kept inside the else block. The else block cannot exist independently. This means that the else statement must follow an if-statement or else if statement. An else statement can only be used once in an if-else statement chain.</p>
<p><strong>The syntax of the if-else statement is –</strong></p>
<pre class="brush:php;toolbar:false">if(a conditional statement or boolean expression)
{
// the block of code to be executed if the expression results into true
}
else
{
// executes when “if” exp is false
}
  • As observed, the else statement does not contain any boolean expression. The block of code following the else statement is always executed whenever the condition is given in the ‘if’ brackets evaluates to be false.
  • We will consider the example of Ravi and Amar’s age as our problem statement for further clarification –

For Example –

using System;
class Ex4
{
static void Main(string[] args)
{
int R_age = 12, A_age = 15;
if ( R_age > A_age)
Console.WriteLine("Ravi is elder to Amar");
else
Console.WriteLine("Ravi and Amar are of the same age");
}
}

Output:

C# if Statement

By now, you must have noticed that the boolean expression in the first ‘if’ statement given as a parameter evaluates to be false as Ravi’s age(12) is less than Amar’s age(15). Like the if statement holds false, the second block, i.e. the code block associated with the else condition, will be executed.

else if Statement

The second type of conditional statement provided by C# is an else if statement. If the given conditions to be checked are more than one, then the else-if conditions come into the picture.

Consider –

using System;
class Ex5
{
static void Main(string[] args)
{
int R_age = 12, A_age = 15;
if ( R_age > A_age)
Console.WriteLine("Ravi is elder");
else if (R_age 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534737077082.png?x-oss-process=image/resize,p_40" class="lazy" alt="C# if Statement" ></p>
<h3 id="Nested-If">Nested If</h3>
<p>Nested if the statement is an if statement within an if statement.</p>
<p><strong>For Example –</strong></p>
<pre class="brush:php;toolbar:false">using System;
class Ex6
{
static void Main(string[] args)
{
int R_age = 12, A_age = 15;
if(R_age != A_age) //yields true as 12 is not equal to 15
{
if( R_age 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534737228914.png?x-oss-process=image/resize,p_40" class="lazy" alt="C# if Statement" ></p>
<h3 id="Conclusion">Conclusion</h3>
<p>The if-else or else-if statement evaluates the boolean expression and, based on the result, controls the flow of the program.</p>

The above is the detailed content of C# if Statement. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.