;

C# Statements


In C#, statements are fundamental units of code execution that instruct the program on what actions to perform. From declaring variables to controlling program flow, C# statements allow developers to implement logic in a structured and readable manner. In this tutorial, we will cover various C# statements, including declaration statements, exception-handling statements, iteration statements, selection statements, jump statements, and specialized statements such as checked/unchecked, fixed, lock, using, and yield.

Declaration Statements

Declaration statements are used to declare variables and constants. They define the type and name of a variable and can optionally initialize it.

Example:

int number = 5;  // Declaring and initializing an integer variable
string message = "Hello, World!";  // Declaring and initializing a string

Use Case:

Declaration statements are used whenever you need to introduce new variables or constants to store data.

Exception-Handling Statements

Exception-handling statements allow you to handle runtime errors in your application gracefully. The try, catch, finally, and throw statements fall under this category.

Example:

try
{
    int result = 10 / 0;  // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
}
finally
{
    Console.WriteLine("Cleanup code here.");
}

Use Case:

Use exception-handling statements when you anticipate runtime errors, such as file handling, network operations, or division by zero, to prevent your program from crashing unexpectedly.

Iteration Statements

Iteration statements (also known as loops) allow you to repeatedly execute a block of code. Common iteration statements include for, while, do...while, and foreach.

Example:

// For loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// While loop
int counter = 0;
while (counter < 5)
{
    Console.WriteLine(counter);
    counter++;
}

Use Case:

Use iteration statements when you need to perform repeated actions, such as iterating over arrays or collections.

Selection Statements

Selection statements allow the program to choose different paths of execution based on certain conditions. These include if, else, else if, and switch statements.

Example:

int number = 10;
if (number > 0)
{
    Console.WriteLine("Positive number");
}
else if (number < 0)
{
    Console.WriteLine("Negative number");
}
else
{
    Console.WriteLine("Zero");
}

// Switch statement
switch (number)
{
    case 1:
        Console.WriteLine("Number is one");
        break;
    case 10:
        Console.WriteLine("Number is ten");
        break;
    default:
        Console.WriteLine("Unknown number");
        break;
}

Use Case:

Selection statements are used to control the flow of execution based on conditions. They're commonly used in decision-making scenarios, such as checking user inputs or program states.

Jump Statements

Jump statements control the flow of the program by moving control to different parts of the code. These include break, continue, goto, return, and throw.

Example:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
        break;  // Exit the loop when i equals 5
    Console.WriteLine(i);
}

void GreetUser(string name)
{
    if (string.IsNullOrEmpty(name))
        return;  // Exit the method early
    Console.WriteLine($"Hello, {name}");
}

Use Case:

Use jump statements when you need to alter the normal flow of execution, such as exiting loops or returning from a method early.

Checked and Unchecked Statements

The checked and unchecked statements control how the system handles overflow during arithmetic operations.

Example:

int maxValue = int.MaxValue;

try
{
    int result = checked(maxValue + 1);  // This will throw an OverflowException
}
catch (OverflowException)
{
    Console.WriteLine("Overflow occurred");
}

int uncheckedResult = unchecked(maxValue + 1);  // This will not throw an exception

Use Case:

Use checked when you want to ensure that arithmetic overflows are detected, and unchecked when you want to ignore overflow checks, typically for performance reasons.

Fixed Statement

The fixed statement is used in unsafe code contexts to prevent the garbage collector from moving a variable. This is typically used with pointers in C#.

Example:

unsafe
{
    int[] numbers = { 1, 2, 3 };
    fixed (int* p = numbers)
    {
        *p = 99;  // Modifying the first element of the array
    }
}

Use Case:

Use the fixed statement when working with pointers in unsafe code, especially when interfacing with low-level memory operations.

Lock Statement

The lock statement is used to ensure that a block of code is executed by only one thread at a time, providing thread safety in multi-threaded environments.

Example:

class BankAccount
{
    private object balanceLock = new object();
    private decimal balance;

    public void Deposit(decimal amount)
    {
        lock (balanceLock)
        {
            balance += amount;
        }
    }
}

Use Case:

Use the lock statement to protect shared resources from being accessed by multiple threads simultaneously, avoiding data corruption.

Using Statement

The using statement ensures that IDisposable objects are properly disposed of after they are no longer needed. This is important for managing resources like files, database connections, etc.

Example:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}  //

Use Case:

Use the using statement to automatically manage the lifetime of resources like file streams, database connections, and other unmanaged resources.

Yield Statement

The yield statement is used to return each element one at a time from a method that returns an IEnumerable. It’s commonly used in iterators.

Example:

public IEnumerable<int> GetNumbers()
{
    for (int i = 0; i < 5; i++)
    {
        yield return i;  // Returns one element at a time
    }
}

foreach (int number in GetNumbers())
{
    Console.WriteLine(number);
}

Use Case:

Use yield in methods that need to return an enumerable sequence, particularly in scenarios involving large data sets where deferred execution is useful.

Key Takeaways

  • Declaration Statements are the backbone of variable and constant initialization.
  • Exception-Handling Statements like try, catch, and finally ensure your program can handle runtime errors gracefully.
  • Iteration Statements (for, while, foreach) simplify looping over collections or repeating tasks.
  • Selection Statements (if, else, switch) provide the decision-making logic in your programs.
  • Jump Statements (break, continue, return, goto) allow you to alter the flow of execution when necessary.
  • Checked and Unchecked Statements control how arithmetic overflow is handled.
  • Fixed Statement is used with pointers to pin variables in memory.
  • Lock Statement ensures thread safety when multiple threads access shared resources.
  • Using Statement simplifies resource management for IDisposable objects.
  • Yield Statement is great for returning elements lazily from an iterator method.

Summary

By mastering these C# statements, you gain full control over your application's logic, making your code more efficient, readable, and robust. Each statement has its use case, and understanding when to apply each one is key to writing clean, maintainable code.