Skip to Content
All posts

Statements In C#

2 min read ·  — #csharp-interview#junior

Statements In C#

In C#, a statement is the smallest standalone element of the language that expresses some action to be carried out. They form the building blocks of your programs. C# offers a wide range of statement types to help you control the flow of your programs.

Let's take a look at some of the key types of statements in C#.

1. Expression Statements:

Expression statements are actions. The most common ones include method calls, assignments, and operations (like incrementing a value).

Example:

Console.WriteLine("Hello, World!");  // method call

int x = 10;  // assignment

x++;  // increment operation

2. Declaration Statements:

Declaration statements are used to declare variables.

Example:

int num;  // declaration of integer variable

// declaration of string variable with initialization
string greeting = "Hello, World!";

3. Selection Statements:

Selection statements are used for decision making and branching.

Example:

int num = 10;

if (num > 5)  // if statement
{
    Console.WriteLine("The number is greater than 5.");
}
else
{
    Console.WriteLine("The number is not greater than 5.");
}

4. Iteration Statements:

Iteration statements are used to perform loops

Example:

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

while (num > 0)  // while loop
{
    Console.WriteLine(num);
    num--;
}

5. Jump Statements:

Jump statements are used to transfer control to another part of the program.

Example:

for (int i = 0; i < 5; i++)
{
    if (i == 2)
        continue;  // jump to next iteration

    if (i == 4)
        break;  // break the loop

    Console.WriteLine(i);
}

6. Try...Catch...Finally Statements:

These are used for exception handling.

Example:


try
{
    int result = 10 / 0;  // this will throw DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
}
finally
{
    Console.WriteLine("This block is always executed.");
}

Conclusion:

These are some of the basic types of C# statements you should be familiar with. During an interview, you might be asked to solve problems or build simple features using these statements. Being comfortable with them is essential for demonstrating your proficiency in C#.

Further Reading: