Statements and types of statements in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 53280 red flag
Rating: 4.5 out of 5  
 2 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read var type, Expressions and Precedence in C# before this article.

Introduction

In previous articles, we have seen var and expressions in C#. Now let's take a look into statements in C# in this chapter.

Objective

The main objective of this article is to know briefly about the statements and its types that are used in C#.

Statements

Statements are the actions of the program which are expressed in. Common actions include methods, variables, values etc.
Execution order of statements in a program is called as flow of control (execution).

Statement block:
A series of statements which are placed in the flower braces that are '{' and '}' is known as Statement block.
It can contain nested blocks.

Declaration Statements:

It declares a new variable or constant with an expression. For variable, it assigns a value and for constant, the assignment is required.
Example:
int a = 4;
string name = "krishna";
We can also declare multiple variables of the same type in a single expression. For example,
int a = 4, b = 5;
bool in = true, out = false;
Constant declaration is similar to variable declaration but, it cannot be changed after the declaration. For example,
const int a = 4;
a = a + 12;      // This will give compile-time error

Expression statements:

These are the valid statements in which they must change the state (variable) or call some other function that might change the state.

Different types of expression statements are,
  • Assignment expressions
  • Increment and decrement expressions
  • Method call expressions
  • Object instantiation expressions.
Examples of different types of expressions are,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            // Declaring variables
            int a, b;
            StringBuilder sb;

            //Expression statements
            a = 2 * 3;                  // Assignment expression
            a++;                        // Increment expression
            b = Math.Min(a, 8);         // Compares and finds the minimum value
            Console.WriteLine(b);       // Method call expression

            a--;                        // Decrement expression
            b = Math.Max(a, 5);         // Compares and finds the maximum value
            Console.WriteLine(b);       // Method call expression

            sb = new StringBuilder();   // Assignment expression
            new StringBuilder();        // Object instantiation expression

        }
    }
}
In the above code we have clearly mentioned the type of expression statements.

Note: please read comments in the code.

Output of this code will be,


Selection statements:

There are so many selection statements in C# such as if, else, case, switch etc. 
if:
Let's have an example code that explains about if statement in c#,
int a = 5, b = 5;

if (a == b)
{
   Console.WriteLine("Both are equal");  // prints "Both are equal" in the console
}
The above code snip executes the statement because both a and b are equal.

else:
else is the statement block that executes after the if block (if condition of if block is false). For example,
int a = 4, b = 5;

if (a == b)
{
    Console.WriteLine("Both are equal");
}
else
{
    Console.WriteLine("Not equal");     // Prints this one 
}
The above code first check's the if statement and then it enters into the else block.

switch, case:
switch statement is used to execute the switched section from the list (case). Let's take an example,
string Fruit = "Mango";
switch (Fruit)
{
    case "Mango":
        Console.WriteLine(Fruit);
        break;
    case "Tomato":
        Console.WriteLine("Not Fruit");
        break;
    default:
        Console.WriteLine("Default");
        break;
}

Iteration statements:

Iteration statements are used to create the loops. Similar to selection statements, iteration statements are also used in many cases where looping and iterating is needed.

do, while:
do statement executes the block of statements repeatedly until it gets false evaluation. For example,
static void Main()
{
    int a = 5, b = 7;
    do
    {
        Console.WriteLine(a);
        a++;
    } 
    while (a <= 10); 
}
In the above code, do loops repeatedly until a becomes 10 because we have given 'a <= 10' in the while statement.

for:
for is similar to do but it iterates without using any other statements like while. Example,
for (int i = 0; i <= 10; i++)
{
    Console.WriteLine(i);       // prints 0 to 10
}
foreach:
This is one of the important statement used in C# and .NET frameworks as they represent the list of elements which are enumerable.
  • It repeats all the embedded statements in a group for each element in an array or an object collection.
  • It cannot be used to add or remove the items from the source (for loop does that).
All the embedded statements continue to execute for the each element of an object or an array. After that, the control is transferred to the next statement following the foreach block.
  • We can also use he break keyword to break out of the loop.
  • We can use continue keyword to go to the next iteration in the loop.
  • It can also be exited by other statements such as return, throw (jump statements) etc.
Example,
foreach (char c in "Hello") // c is the iteration variable in the statement
{
    Console.WriteLine(c);   // prints all the characters of the string.
}

Jump statements:

Jump statements are used to perform the branching operations in C#. break, continue, return, throw and goto are the jump statements used in C#.

break:
break is used to terminate the execution at that point (that function). Example,
for (int i = 0; i <= 10; i++)
{
    if (i == 3)
    {
        break;                 // It stops terminates the execution at i=3 and prints the before executed outputs
    }
    Console.WriteLine(i);
}
In the above code, i prints 0, 1 and 2 and terminates the execution.

continue:
continue is used to start the execution at certain point as shown in the below example,
for (int i = 0; i <= 10; i++)
{
    if (i < 5)
    {
        continue;                 // It continues the execution at i=4 and prints the after executed outputs
    }
    Console.WriteLine(i);
}
The above code prints the values from 5 as we given 'i < 5' in the if statement.

return:
return statement exits the method by returning an expression of the return type for a non-void method. Example,
static decimal Percentage(decimal b)
{
    decimal a = b*100m;
    return a;
}

throw:
It throws an exception that indicates an occurred error. It is an object derived from System.Exception. Example,
throw new ArgumentNullException();

goto:
goto statement transfers the execution of program to another label directly. Syntax is,
goto statement-label; // for normal statements
and,
goto case case-constant; // for switch statement
  • In switch-case statements, it transfers the execution to another case in a switch block.
  • It also used to get out from the deep nested loops.
Example for goto statement,
int a = 5;
Begin:
if (a <= 10)
{
    Console.WriteLine(a + "");
    a++;
    goto Begin;
}

Conclusion

In this article, we have seen different types of statements that are used in C#. Hope you understand.

Thanks for reading,

Regards,
Krishna.

Recommendation
Read Namespaces and Using directive in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Posted by: Nitesh Khandelwal on: 8/20/2014 | Points: 25
Awesome article !! such an informative article, which present complete knowledge of statements and its type like conditional statements, declaration statements, control statements with syntax and examples.This can be an important aspect while concerning for .Net coding for fresher trainees. http://www.sagacademy.com/dotnet-development-training-jaipur
Posted by: Goud.Kv on: 8/27/2014 | Points: 25
Thank you Nitesh,

Regards,
Krishna.

Login to post response

Comment using Facebook(Author doesn't get notification)