2. Control Flow


1. Decision Making Statements

if Statement

int age = 18;

if (age >= 18)
{
    Console.WriteLine("Adult");
}

Syntax:

if (condition)
{
    // Code executes if condition is true
}

if-else Statement

int age = 15;

if (age >= 18)
{
    Console.WriteLine("Adult");
}
else
{
    Console.WriteLine("Minor");
}

if-else-if Ladder

Nested if Statements

Ternary Operator (?:)

switch Statement (Traditional) - C# 1.0

Key Points:

  • Each case must end with break, return, or goto

  • C# does NOT have fall-through (unlike C/C++)

  • Multiple cases can share same code block

  • default is optional but recommended

No Fall-Through in C#:

switch Expressions - C# 8.0+

Much more concise and returns a value

Syntax:

More Examples:

Pattern Matching in switch

Type Patterns (C# 7.0+)

Property Patterns (C# 8.0+)

Tuple Patterns (C# 8.0+)

Positional Patterns (C# 8.0+)

Relational Patterns (C# 9.0+)

Logical Patterns (C# 9.0+)

List Patterns (C# 11.0+)

Pattern Matching Evolution Table

Version
Feature
Example

C# 7.0

Type patterns

case string s:

C# 7.0

var pattern

case var x:

C# 8.0

Property patterns

{ Age: > 18 }

C# 8.0

Tuple patterns

(1, 2) => ...

C# 8.0

Positional patterns

Point(0, 0) => ...

C# 8.0

Switch expressions

value switch { ... }

C# 9.0

Relational patterns

>= 0 and < 100

C# 9.0

Logical patterns

and, or, not

C# 11.0

List patterns

[1, 2, ..]


2. Loops

for Loop

Syntax:

Basic Example:

Multiple Variables:

Infinite Loop:

Variations:

while Loop

Syntax:

Example:

Infinite Loop:

do-while Loop

Syntax:

Key Difference: Executes at least once (condition checked after)

foreach Loop

Syntax:

With Arrays:

With Collections:

await foreach (C# 8.0+)

Nested Loops

Loop Comparison:

Loop Type
When to Use

for

Know iteration count, need index

while

Don't know iteration count, check before

do-while

Must execute at least once

foreach

Iterate over collection, don't need index


3. Jump Statements

break

Exits loop or switch immediately

continue

Skip rest of current iteration, continue with next

return

Exit method and optionally return value

goto (Discouraged)

Jump to labeled statement

throw

Throw exception (exits to exception handler)


4. Arrays Deep Dive

Single-Dimensional Arrays

Declaration and Initialization:

Accessing Elements:

Length Property:

Multi-Dimensional Arrays (Rectangular)

3D Arrays:

Jagged Arrays (Array of Arrays)

Rectangular vs Jagged:

Feature

Rectangular [,]

Jagged [][]

Memory

Single contiguous block

Multiple arrays

Size

All rows same length

Rows can vary

Access

arr[i, j]

arr[i][j]

Performance

Faster access

Slower access

Flexibility

Fixed structure

Variable row lengths

Use when

Matrix, grid

Irregular data

Array Class Methods

Collection Expressions (C# 12.0+)


5. Strings Deep Dive

String Properties

String Methods Reference Table

Method
Description
Example
Result

Substring(start)

Get substring from start

"Hello".Substring(1)

"ello"

Substring(start, length)

Get substring with length

"Hello".Substring(1, 3)

"ell"

Replace(old, new)

Replace all occurrences

"Hello".Replace("l", "L")

"HeLLo"

Trim()

Remove whitespace from both ends

" Hi ".Trim()

"Hi"

TrimStart()

Remove from start

" Hi ".TrimStart()

"Hi "

TrimEnd()

Remove from end

" Hi ".TrimEnd()

" Hi"

ToUpper()

Convert to uppercase

"hello".ToUpper()

"HELLO"

ToLower()

Convert to lowercase

"HELLO".ToLower()

"hello"

ToUpperInvariant()

Culture-independent upper

"hello".ToUpperInvariant()

"HELLO"

ToLowerInvariant()

Culture-independent lower

"HELLO".ToLowerInvariant()

"hello"

StartsWith(value)

Check if starts with

"Hello".StartsWith("He")

true

EndsWith(value)

Check if ends with

"Hello".EndsWith("lo")

true

Contains(value)

Check if contains

"Hello".Contains("ll")

true

Split(separator)

Split into array

"a,b,c".Split(',')

["a","b","c"]

Join(separator, array)

Join array elements

String.Join("-", arr)

"a-b-c"

IndexOf(value)

Find first occurrence

"Hello".IndexOf("l")

2

LastIndexOf(value)

Find last occurrence

"Hello".LastIndexOf("l")

3

Insert(index, value)

Insert at position

"Hlo".Insert(1, "el")

"Hello"

Remove(start)

Remove from start

"Hello".Remove(3)

"Hel"

Remove(start, count)

Remove count chars

"Hello".Remove(1, 3)

"Ho"

PadLeft(width)

Pad left with spaces

"Hi".PadLeft(5)

" Hi"

PadLeft(width, char)

Pad with character

"Hi".PadLeft(5, '0')

"000Hi"

PadRight(width)

Pad right

"Hi".PadRight(5)

"Hi "

Compare(s1, s2)

Compare (static)

String.Compare("a","b")

-1

CompareTo(other)

Compare instance

"a".CompareTo("b")

-1

Equals(other)

Check equality

"Hi".Equals("Hi")

true

Format(format, args)

Format string (static)

String.Format("{0}", 5)

"5"

Concat(strings)

Concatenate (static)

String.Concat("a","b")

"ab"

String Manipulation

Concatenation

String Interpolation ($"")

Composite Formatting (String.Format)

String vs StringBuilder

String (Immutable):

StringBuilder (Mutable):

StringBuilder Methods:

When to Use:

String
StringBuilder

Few concatenations (< 5)

Many concatenations

Immutability needed

Building string in loop

Thread-safe (immutable)

Single-threaded building

Small strings

Large strings

Performance Comparison:

Escape Sequences


Common Loop Patterns

Sum of Numbers

Find Maximum

Count Occurrences

Reverse Array

Filter Array


String Manipulation Recipes

Split and Join

Remove Whitespace

Extract Substring

Check if String is Numeric

Capitalize First Letter

Reverse String


Common Pitfalls

1. Off-by-One Errors

2. Modifying Collection During foreach

3. String Concatenation in Loop

4. Forgetting break in switch

5. Infinite Loops


Best Practices

1. Use foreach When You Don't Need Index

2. Use Switch Expressions for Simple Mappings

3. Use Pattern Matching for Type Checks

4. Use String Interpolation Over Concatenation

5. Validate Loop Bounds

6. Use Collection Expressions (C# 12.0+)

7. Use Early Returns to Reduce Nesting

8. Use StringBuilder for Repeated Concatenation


Quick Reference Summary

Control Flow

  • if/else - Basic branching

  • switch - Multiple cases

  • switch expression - Modern, returns value

  • Ternary (?:) - Inline condition

Loops

  • for - Known iterations, need index

  • while - Condition checked first

  • do-while - Executes at least once

  • foreach - Iterate collections

Jump Statements

  • break - Exit loop/switch

  • continue - Skip iteration

  • return - Exit method

  • goto - Jump to label (avoid)

Arrays

  • Single-dimensional - int[]

  • Multi-dimensional - int[,]

  • Jagged - int[][]

Strings

  • Immutable - Cannot change after creation

  • Use StringBuilder - For many concatenations

  • String interpolation - Modern formatting


Last updated