Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps
   ❮   
     ❯   

C#If ... Else


C# Conditions and If Statements

You already know that C# supports familiar comparison conditions from mathematics, such as:

  • Less than:a < b
  • Less than or equal to:a <= b
  • Greater than:a > b
  • Greater than or equal to:a >= b
  • Equal toa == b
  • Not Equal to:a != b

You can use these conditions to perform different actions for different decisions.

C# has the following conditional statements:

  • Useif to specify a block of code to be executed, if a specified condition is true
  • Useelse to specify a block of code to be executed, if the same condition is false
  • Useelse if to specify a new condition to test, if the first condition is false
  • Useswitch to specify many alternative blocks of code to be executed

The if Statement

Use theif statement to specify a block of C# code to be executed if a condition isTrue.

Syntax

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

Note thatif is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition isTrue, print some text:

Example

if (20 > 18) {  Console.WriteLine("20 is greater than 18");}

Try it Yourself »

We can also test variables:

Example

int x = 20;int y = 18;if (x > y) {  Console.WriteLine("x is greater than y");}

Try it Yourself »

Example explained

In the example above we use two variables,x andy, to test whether x is greater than y (using the> operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2026 Movatter.jp