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 are used to declare variables and constants. They define the type and name of a variable and can optionally initialize it.
int number = 5; // Declaring and initializing an integer variable
string message = "Hello, World!"; // Declaring and initializing a string
Declaration statements are used whenever you need to introduce new variables or constants to store data.
Exception-handling statements allow you to handle runtime errors in your application gracefully. The try
, catch
, finally
, and throw
statements fall under this category.
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 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 (also known as loops) allow you to repeatedly execute a block of code. Common iteration statements include for
, while
, do...while
, and foreach
.
// 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 iteration statements when you need to perform repeated actions, such as iterating over arrays or collections.
Selection statements allow the program to choose different paths of execution based on certain conditions. These include if
, else
, else if
, and switch
statements.
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;
}
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 control the flow of the program by moving control to different parts of the code. These include break
, continue
, goto
, return
, and throw
.
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 jump statements when you need to alter the normal flow of execution, such as exiting loops or returning from a method early.
The checked
and unchecked
statements control how the system handles overflow during arithmetic operations.
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 checked when you want to ensure that arithmetic overflows are detected, and unchecked when you want to ignore overflow checks, typically for performance reasons.
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#.
unsafe
{
int[] numbers = { 1, 2, 3 };
fixed (int* p = numbers)
{
*p = 99; // Modifying the first element of the array
}
}
Use the fixed statement when working with pointers in unsafe code, especially when interfacing with low-level memory operations.
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.
class BankAccount
{
private object balanceLock = new object();
private decimal balance;
public void Deposit(decimal amount)
{
lock (balanceLock)
{
balance += amount;
}
}
}
Use the lock statement to protect shared resources from being accessed by multiple threads simultaneously, avoiding data corruption.
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.
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
} //
Use the using statement to automatically manage the lifetime of resources like file streams, database connections, and other unmanaged resources.
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.
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 yield
in methods that need to return an enumerable sequence, particularly in scenarios involving large data sets where deferred execution is useful.
try
, catch
, and finally
ensure your program can handle runtime errors gracefully.for
, while
, foreach
) simplify looping over collections or repeating tasks.if
, else
, switch
) provide the decision-making logic in your programs.break
, continue
, return
, goto
) allow you to alter the flow of execution when necessary.IDisposable
objects.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.