C# Programming Tutorial: From Fundamentals to Advanced Application Development

2.01K 0 0 0 0

📘 Chapter 3: Control Flow and Error Handling in C#

🧠 Introduction

A real-world program needs more than just logic—it needs the ability to make decisions, repeat tasks, and handle errors gracefully. This chapter explores control flow statements that allow branching and looping, along with error handling techniques in C#.


🔄 1. Control Flow in C#

Control flow determines how and when different parts of your code get executed. In C#, it includes:

  • Conditional Statements (if, else, switch)
  • Looping Statements (for, while, do-while, foreach)
  • Jump Statements (break, continue, return, goto)

2. Conditional Statements

🔹 if Statement

Executes code only if a condition is true.

int age = 18;

 

if (age >= 18)

{

    Console.WriteLine("You are eligible to vote.");

}


🔹 if-else Statement

Provides an alternate block if the condition is false.

if (age < 18)

{

    Console.WriteLine("Not eligible.");

}

else

{

    Console.WriteLine("Eligible.");

}


🔹 else if Ladder

Used for multiple conditions.

int marks = 75;

 

if (marks >= 90)

    Console.WriteLine("Grade A");

else if (marks >= 75)

    Console.WriteLine("Grade B");

else

    Console.WriteLine("Grade C");


🔹 switch Statement

Efficient for multiple discrete values.

int day = 3;

 

switch (day)

{

    case 1: Console.WriteLine("Monday"); break;

    case 2: Console.WriteLine("Tuesday"); break;

    case 3: Console.WriteLine("Wednesday"); break;

    default: Console.WriteLine("Invalid Day"); break;

}


📋 Comparison Table – Conditionals

Statement

Use Case

Fallthrough

if

Single condition

No

if-else

Dual path

No

else-if

Multiple conditions

No

switch

Multiple fixed values

Yes (without break)


🔁 3. Looping Statements

Used for repeating code blocks.


🔹 for Loop

Used when the number of iterations is known.

for (int i = 0; i < 5; i++)

{

    Console.WriteLine(i);

}


🔹 while Loop

Executes while a condition is true.

int i = 0;

while (i < 5)

{

    Console.WriteLine(i);

    i++;

}


🔹 do-while Loop

Always executes at least once.

int j = 0;

do

{

    Console.WriteLine(j);

    j++;

} while (j < 5);


🔹 foreach Loop

Iterates over collections.

string[] colors = { "Red", "Green", "Blue" };

 

foreach (string color in colors)

{

    Console.WriteLine(color);

}


📋 Comparison Table – Loops

Loop Type

Entry/Exit Check

When to Use

for

Entry

Known iteration count

while

Entry

Unknown count; pre-check

do-while

Exit

At least once execution

foreach

Entry

Collections/arrays


🚀 4. Jump Statements


🔹 break

Exits a loop or switch.

for (int i = 1; i <= 5; i++)

{

    if (i == 3)

        break;

    Console.WriteLine(i); // 1 2

}


🔹 continue

Skips to next iteration.

for (int i = 1; i <= 5; i++)

{

    if (i == 3)

        continue;

    Console.WriteLine(i); // 1 2 4 5

}


🔹 return

Exits the method and optionally returns a value.

int GetNumber()

{

    return 42;

}


🔹 goto (use with caution)

Used to jump to a labeled statement.

int i = 0;

 

start:

if (i < 3)

{

    Console.WriteLine(i++);

    goto start;

}


️ 5. Error Handling in C#

Errors are inevitable. Without proper handling, they can crash your program. C# provides structured exception handling using:

  • try
  • catch
  • finally
  • throw

try-catch Block

try

{

    int x = 5, y = 0;

    Console.WriteLine(x / y); // Division by zero!

}

catch (DivideByZeroException e)

{

    Console.WriteLine("Error: " + e.Message);

}


Multiple catch Blocks

try

{

    int[] arr = { 1, 2 };

    Console.WriteLine(arr[5]);

}

catch (IndexOutOfRangeException e)

{

    Console.WriteLine("Index out of range");

}

catch (Exception ex)

{

    Console.WriteLine("General error");

}


finally Block

Executes regardless of exception.

try

{

    Console.WriteLine("Try block");

}

finally

{

    Console.WriteLine("Always runs");

}


throw Statement

Used to manually raise exceptions.

throw new InvalidOperationException("Invalid operation");


📦 Common Exception Types in C#

Exception Type

When It Occurs

DivideByZeroException

Division by zero

NullReferenceException

Accessing members on null objects

IndexOutOfRangeException

Array or list index invalid

FormatException

Invalid data type conversions

InvalidOperationException

Operation not valid in current state

IOException

File or I/O errors


🧪 Sample Program: Error Handling Example

using System;

 

class Program

{

    static void Main()

    {

        try

        {

            Console.Write("Enter a number: ");

            int num = Convert.ToInt32(Console.ReadLine());

 

            Console.WriteLine("Reciprocal: " + (1.0 / num));

        }

        catch (DivideByZeroException)

        {

            Console.WriteLine("Cannot divide by zero.");

        }

        catch (FormatException)

        {

            Console.WriteLine("Invalid input.");

        }

        finally

        {

            Console.WriteLine("Execution completed.");

        }

    }

}


🧠 Best Practices for Control Flow and Error Handling

  • Avoid deeply nested if statements—use switch or early returns.
  • Handle only specific exceptions, not Exception base class unless necessary.
  • Always close file/database connections in finally or use using.
  • Never use goto unless there’s a very clear use case.

📋 Summary Table


Concept

Use

if, else, switch

Decision making

for, while, do-while, foreach

Looping

break, continue, return, goto

Jumping in logic

try, catch, finally, throw

Structured error handling

Back

FAQs


1. Q: Is C# easy to learn for beginners?

A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.

2. Q: Do I need to know C or C++ before learning C#?

A: Not at all. C# is independent and designed for new learners.

3. Q: Can I build web apps using C#?

A: Yes, using ASP.NET Core you can build scalable web apps and APIs.

4. Q: What’s the difference between C# and Java?

A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.

5. Q: Is C# only for Windows development?

A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.

6. Q: Is C# good for game development?

A: Absolutely. It is the main language used in Unity.

7. Q: Which IDE is best for C#?

A: Visual Studio is the most powerful and popular IDE for C# development.

8. Q: Can I use C# for mobile development?

 A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.

9. Q: What is the future of C# in 2025 and beyond?

A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.

10. Q: Do I need internet to use C# tools?

A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.