How to use the return statement in C#?

CsharpProgrammingServer Side Programming

The return statement is used to return value. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

The following is an example to learn about the usage of return statement in C#. Here, we are finding the factorial of a number and returning the result using the return statement.

while (n != 1) {
   res = res * n;
   n = n - 1;
}
return res;

Here is the complete example.

Example

 Live Demo

using System;
namespace Demo {
   class Factorial {
      public int display(int n) {
         int res = 1;
         while (n != 1) {
            res = res * n;
            n = n - 1;
         }
         return res;
      }
      static void Main(string[] args) {
         int value = 5;
         int ret;
         Factorial fact = new Factorial();
         ret = fact.display(value);
         Console.WriteLine("Value is : {0}", ret );
         Console.ReadLine();
      }
   }
}

Output

Value is : 120
raja
Published on 18-Sep-2018 13:18:08
Advertisements