Lesson 6.4

Return Statement c# - Programming Example


Objective

What is return statement in c#?
Programming Example

What is return statement in C#?

Return statement pull the execution control from the current method and sends it where the method was invoked. It exits execution control from the current method. In C# return statement is used by two types.

  1. Simple return statement which nothing return just exits from the current method.
  2. A return statement which returns a value also.

Programming Example

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

namespace return_statements
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Program Started");
            count();
            Console.WriteLine("Return from count method");
            Console.ReadKey();
        }

        public static void count()
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine(i);
                if (i == 7)
                {
                    Console.WriteLine("Return is Invoked");
                    return;
                }
                i++;
            }
        }
    }
}

Output

Program Started
0
1
2
3
4
5
6
7
Return is Invoked
Return from count method
__

Explanation:

In this program, we have create a method count() which simply print number with the help of while loop. Inside a while loop there is a condition tested and when it becomes true the count method return execution to main method again.

Summary

In this chapter you have learned what return statement is in C# and how to use it in programming language. In the next chapter you will learn about checked and unchecked statement.

BackNext