Control structures
Selection statements
if-else
- Accoladers niet nodig wanneer slechts 1 statement erin staat (ook zo bij alle iteratie structuren)
- docs
if (true)
Run();
else
Stop();
bool Condition1 = true;
bool Condition2 = true;
bool Condition3 = true;
bool Condition4 = true;
if (Condition1) {
// Condition1 is true.
}
else if (Condition2) {
// Condition1 is false and Condition2 is true.
}
else if (Condition3) {
if (Condition4) {
// Condition1 and Condition2 are false. Condition3 and Condition4 are true.
}
else {
// Condition1, Condition2, and Condition4 are false. Condition3 is true.
}
}
else {
// Condition1, Condition2, and Condition3 are false.
}
switch
- keywords
case
default
when
- elke switch section moet een jump statement hebben:
break
continue
goto
return
throw
- docs
Random rnd = new Random();
int caseSwitch = rnd.Next(1,4);
switch (caseSwitch) {
case 1: // eerste switch section begint hier
Console.WriteLine("Case 1");
break; // jump statement
case 2: // tweede switch section begint hier
case 3: // de volgende twee statements gelden voor case 2 en 3
Console.WriteLine($"Case {caseSwitch}");
goto case 1; // jump statement
default: // derde switch section begint hier
Console.WriteLine($"An unexpected value ({caseSwitch})");
throw new NotImplementedException(); // jump statement
}
Voorbeeld van de when
clause en van pattern matching.
public static double ComputeArea_Version3(object shape)
{
switch (shape)
{
case Square s when s.Side == 0:
case Circle c when c.Radius == 0:
return 0;
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}
Iteration statements
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
Console.WriteLine(element);
}
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
int x = 0;
do
{
Console.WriteLine(x);
x++;
} while (x < 5);