C# & ASP.NET Topic

C# Control Flow structures

Control flow statements are the building blocks that determine the order in which your code executes.

1. Conditional Statements

if/else Statements

The if/else statement allows you to execute different code blocks based on boolean conditions.

Basic Syntax:

csharp

if (condition)
{
    // Code to execute if condition is true
}
else if (anotherCondition)
{
    // Code to execute if anotherCondition is true
}
else
{
    // Code to execute if all conditions are false
}

Detailed Examples:

Simple if/else:

csharp

int temperature = 25;

if (temperature > 30)
{
    Console.WriteLine("It's hot outside!");
}
else if (temperature > 20)
{
    Console.WriteLine("It's warm outside!");  // This will execute
}
else
{
    Console.WriteLine("It's cool outside!");
}

Nested if statements:

csharp

int age = 25;
bool hasLicense = true;

if (age >= 18)
{
    Console.WriteLine("You're an adult.");
    
    if (hasLicense)
    {
        Console.WriteLine("You can drive a car!");  // This will execute
    }
    else
    {
        Console.WriteLine("You need to get a license.");
    }
}
else
{
    Console.WriteLine("You're a minor.");
}

Complex conditions with logical operators:

csharp

int score = 85;
bool completedAssignment = true;

if (score >= 90 && completedAssignment)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 80 && completedAssignment)
{
    Console.WriteLine("Grade: B");  // This will execute
}
else if (score >= 70 || !completedAssignment)
{
    Console.WriteLine("Grade: C - Need improvement");
}
else
{
    Console.WriteLine("Grade: F");
}

Advanced Pattern: Conditional (Ternary) Operator

csharp

int number = 10;
string result = number % 2 == 0 ? "Even" : "Odd";
Console.WriteLine(result);  // Output: "Even"

// Equivalent to:
if (number % 2 == 0)
{
    result = "Even";
}
else
{
    result = "Odd";
}

2. switch Statement

The switch statement provides a cleaner alternative to multiple if/else if statements when testing a single variable against multiple constant values.

Basic Syntax:

csharp

switch (expression)
{
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no cases match
        break;
}

Detailed Examples:

Simple switch:

csharp

DayOfWeek day = DayOfWeek.Monday;

switch (day)
{
    case DayOfWeek.Monday:
        Console.WriteLine("Start of the work week");
        break;
    case DayOfWeek.Friday:
        Console.WriteLine("Thank God it's Friday!");
        break;
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday:
        Console.WriteLine("Weekend!");  // Multiple cases same code
        break;
    default:
        Console.WriteLine("Regular work day");
        break;
}

Switch with patterns (C# 7.0+):

csharp

object obj = 42;

switch (obj)
{
    case int i when i > 0:
        Console.WriteLine($"Positive integer: {i}");
        break;
    case int i when i < 0:
        Console.WriteLine($"Negative integer: {i}");
        break;
    case string s:
        Console.WriteLine($"String with length: {s.Length}");
        break;
    case null:
        Console.WriteLine("Object is null");
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}

Switch expressions (C# 8.0+):

csharp

int score = 85;
string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",  // This will match
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"       // Default case
};

Console.WriteLine($"Grade: {grade}");  // Output: "Grade: B"

3. Loop Structures

for Loop

Used when you know exactly how many times you want to iterate.

Syntax:

csharp

for (initialization; condition; iteration)
{
    // Code to repeat
}

Detailed Examples:

Basic for loop:

csharp

for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Iteration: {i}");
}
// Output: Iteration: 0, Iteration: 1, ..., Iteration: 4

Complex for loop:

csharp

// Sum numbers from 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++)
{
    sum += i;
    Console.WriteLine($"Current sum: {sum}, i: {i}");
}
Console.WriteLine($"Final sum: {sum}");  // Output: 55

Multiple variables in for loop:

csharp

for (int i = 0, j = 10; i < j; i++, j--)
{
    Console.WriteLine($"i: {i}, j: {j}");
}
// Output: 
// i: 0, j: 10
// i: 1, j: 9
// ...
// i: 4, j: 6

while Loop

Repeats a block of code while a condition is true. The condition is checked before each iteration.

Syntax:

csharp

while (condition)
{
    // Code to repeat
}

Detailed Examples:

Basic while loop:

csharp

int count = 0;
while (count < 3)
{
    Console.WriteLine($"Count: {count}");
    count++;
}
// Output: Count: 0, Count: 1, Count: 2

Reading user input with while:

csharp

string input = "";
while (input.ToLower() != "exit")
{
    Console.Write("Enter a command (type 'exit' to quit): ");
    input = Console.ReadLine();
    Console.WriteLine($"You entered: {input}");
}

Infinite loop with break:

csharp

int number = 0;
while (true)  // Infinite loop
{
    number++;
    if (number > 5)
    {
        break;  // Exit the loop
    }
    Console.WriteLine(number);
}
// Output: 1, 2, 3, 4, 5

do-while Loop

Similar to while, but the condition is checked after each iteration, guaranteeing at least one execution.

Syntax:

csharp

do
{
    // Code to repeat
} while (condition);

Detailed Examples:

Basic do-while:

csharp

int x = 0;
do
{
    Console.WriteLine($"x = {x}");
    x++;
} while (x < 3);
// Output: x = 0, x = 1, x = 2

Guaranteed execution example:

csharp

string userInput;
do
{
    Console.Write("Enter 'yes' to continue: ");
    userInput = Console.ReadLine();
} while (userInput.ToLower() != "yes");

Console.WriteLine("Thank you for saying yes!");

foreach Loop

Iterates over each element in a collection (arrays, lists, etc.).

Syntax:

csharp

foreach (var item in collection)
{
    // Code to execute for each item
}

Detailed Examples:

Looping through arrays:

csharp

string[] fruits = { "apple", "banana", "orange" };

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
// Output: apple, banana, orange

Looping through lists:

csharp

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = 0;

foreach (int number in numbers)
{
    sum += number;
    Console.WriteLine($"Current number: {number}, Running sum: {sum}");
}
Console.WriteLine($"Total sum: {sum}");  // Output: 15

Using var with foreach:

csharp

var names = new[] { "Alice", "Bob", "Charlie" };

foreach (var name in names)
{
    Console.WriteLine($"Hello, {name}!");
}

4. Loop Control Statements

break and continue

break - exits the loop entirely
continue - skips the current iteration and moves to the next one

Examples:

Using break:

csharp

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break;  // Exit loop when i reaches 5
    }
    Console.WriteLine(i);
}
// Output: 0, 1, 2, 3, 4

Using continue:

csharp

for (int i = 0; i < 5; i++)
{
    if (i == 2)
    {
        continue;  // Skip iteration when i is 2
    }
    Console.WriteLine(i);
}
// Output: 0, 1, 3, 4

Practical example with both:

csharp

for (int i = 1; i <= 10; i++)
{
    if (i % 3 == 0)
    {
        continue;  // Skip multiples of 3
    }
    
    if (i > 7)
    {
        break;  // Stop after 7
    }
    
    Console.WriteLine(i);
}
// Output: 1, 2, 4, 5, 7

5. Real-World Practical Examples

Example 1: User Menu System

csharp

bool running = true;
while (running)
{
    Console.WriteLine("\n=== MENU ===");
    Console.WriteLine("1. Add item");
    Console.WriteLine("2. View items");
    Console.WriteLine("3. Exit");
    Console.Write("Choose an option: ");
    
    string choice = Console.ReadLine();
    
    switch (choice)
    {
        case "1":
            Console.WriteLine("Adding item...");
            // Add item logic
            break;
        case "2":
            Console.WriteLine("Viewing items...");
            // View items logic
            break;
        case "3":
            Console.WriteLine("Goodbye!");
            running = false;
            break;
        default:
            Console.WriteLine("Invalid option. Try again.");
            break;
    }
}

Example 2: Data Processing Pipeline

csharp

List<string> data = new List<string> { "item1", "skip", "item2", "error", "item3" };

foreach (var item in data)
{
    if (item == "skip")
    {
        Console.WriteLine("Skipping item...");
        continue;
    }
    
    if (item == "error")
    {
        Console.WriteLine("Error encountered! Stopping processing.");
        break;
    }
    
    Console.WriteLine($"Processing: {item}");
    
    // Simulate processing
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine($"  Step {i + 1} completed");
    }
}

Example 3: Nested Loops Pattern

csharp

// Multiplication table
Console.WriteLine("Multiplication Table:");
for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= 5; j++)
    {
        Console.Write($"{i * j,4}");  // 4-character width
    }
    Console.WriteLine();  // New line after each row
}

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?