C# Programming/Keywords/if

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The if keyword identifies an if statement with the following syntax:

if-statement ::= "if" "(" condition ")" if-body ["else" else-body]
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

If the condition evaluates to true, the if-body executes. Curly braces ("{" and "}") allow the if-body to contain more than one statement. Optionally, an else clause can immediately follow the if-body, providing code to execute when the condition is false. Making the else-body another if statement creates the common cascade of if, else if, else if, else if, else statements:

using System;

public class IfStatementSample
    public void IfMyNumberIs()
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");

The boolean expression used in an if statement typically contains one or more of the following operators:

Operator Meaning Operator Meaning
< less than > greater than
== equal to != not equal to
<= less than or equal to >= greater than or equal to
&& and || or
! not

See also else.

C# Keywords
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where