Return statement in C#

In this article we will learn about Return statement in C#.
  • 5425

Introduction

The return statement is used to terminates execution of the method in which it appears and returning value to the caller from the called function. It can also return an optional value. If the method is avoid type, the return statement can not be used.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Return_Statement

{

    class Program

    {

        public int add(int num1, int num2)

        {

            // returns the add of num1 and num2

            return num1 + num2;

        }

        static void Main(string[] args)

        {

            Program p = new Program();

            int result;

            // calling the function add that will return 10 to the result vaiable.

            result = p.add(2, 8);

            Console.WriteLine(result);

            Console.ReadLine();

        }

    }

}

 

In this example the variable result calls the function add() with two parameters and the function add() returns addition of both number to the result variable using return keyword.

 

The output of following program


Clipboard184.jpg

© 2020 DotNetHeaven. All rights reserved.