Lesson 6.1

Block and Empty statements in C# - with programming example


Objective

What is Block keywords in c#?
What is Empty statements in c#?
Programming Example

Block Statements

A block statement is nothing just a block of braces. For example, when you use while loop; there is an opening and closing braces ({}) to write looping statements. It is called block of code. Using block you may write multiple set of statements in a single block.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace blk
{//blk Block Started
    class Program
    {//Program Block Started
        static void Main(string[] args)
        {// Main Block Started
            int x, y, z;
            x = 5;
            y = 10;
            z = x + y;
            Console.WriteLine(z);
            Console.ReadKey();
        }//End Main Block
    }//End Program Block
}//End blk Block

Output

15
__

Empty Statements:

An empty statement does nothing. It is just an empty block of code. It transfers execution control at the end. It is very useful when you don't want to perform any operation but statement is required. It is useful in while loop where you want to a null body but it starts infinite loop. Press ctrl + c to terminate the execution of program.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace empty_statements
{
    class Program
    {
        static int ans;
        static void Main(string[] args)
        {
            while (answer())
                ;
        }
        static bool answer()
        {
            Console.WriteLine("Press 1 for continue and Press 2 for exit\n");
            ans=Convert.ToInt32(Console.ReadLine());
            if (ans == 1)
            {
                Console.WriteLine("Hello this is empty statement example\n");
                return true;
            }
            else
            {
                Console.WriteLine("Thanks for using this program. Press Enter for Exit\n");
                Console.ReadKey();
                return false;
            }
        }
    }
}

		 

Output

Press 1 for continue and Press 2 for exit

1
Hello this is empty statement example

Press 1 for continue and Press 2 for exit

2
Thanks for using this program. Press Enter for Exit
__

Summary

In this chapter you have learned about block and empty statements. In the next chapter you will learn about goto label statement.

BackNext