Jump to content
Wikibooks The Free Textbook Project

C# Programming/Keywords/else

From Wikibooks, open books for an open world
The latest reviewed version was checked on 16 April 2020. There are template/file changes awaiting review.

The else keyword identifies a else clause of 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

An else clause immediately follows an if-body. It provides code to execute when the condition is false. Making the else-body another if statement creates the common cascade of if, elseif, elseif, elseif, else statements:

usingSystem;
publicclassIfStatementSample
{
publicvoidIfMyNumberIs()
{
intmyNumber=5;
if(myNumber==4)
Console.WriteLine("This will not be shown because myNumber is not 4.");
elseif(myNumber<0)
{
Console.WriteLine("This will not be shown because myNumber is not negative.");
}
elseif(myNumber%2==0)
Console.WriteLine("This will not be shown because myNumber is not even.");
else
{
Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
}
}
}

The above example only checks whether myNumber is less than 0, if myNumber is not 4. It in turn only checks whether myNumber%2 is 0, if myNumber is not less than 0. Since none of the conditions are true, it executes the body of the final else clause.



C# Keywords
Special C# Identifiers (Contextual Keywords)
Contextual Keywords (Used in Queries)

AltStyle によって変換されたページ (->オリジナル) /