Branching and Looping in C#, Part 2 - The return statement
(Page 5 of 6 )
The return statement is used commonly with methods in two scenarios. You can use the return statement with a void method to exit to the caller; note that code which comes after the return method will not be executed, as in the following example
public class Loops
{
static void Main(string[] args)
{
TestMethod();
Console.ReadLine();
}
static void TestMethod()
{
Console.WriteLine("Here we will return");
return;
Console.WriteLine("Do you see this line?");
}
}
The result of this application is:

The method call after the return statement will not execute, because return will terminate the method call and return to the caller. The common use of return is to return a value to the caller other than void, so it will be used with methods that has a return type. It's not clear that the return statement call must be the last statement in the method body, but if you use it in combination with the if statement, you can write code like the following:
if( x == -1)
{
return -1;
}
else
{
return 0;
}
This code specifies the return value depending on some other test; actually, you will use it with methods that call Stored Procedures to specify the return value from the data tier to the business tier. Let's take an example of returning a value other than void:
using System;
namespace MyCompany
{
public class Loops
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
int temp = TestNumber(Convert.ToInt32(Console.ReadLine()));
if(temp == 1)
{
Console.WriteLine("This is an EVEN number");
}
else
{
Console.WriteLine("This is an ODD number");
}
Console.ReadLine();
}
static int TestNumber(int x)
{
if(x % 2 == 0)
{
return 1;
}
else
{
return 0;
}
}
}
}
The return statement has been used to return 1 in the case of an even number and 0 in the case of an odd number. The return value has been assigned to a local variable of the Main method. Note that the compiler can do an implicit conversion of the return value in order to return a value of the method's return value so you can't return a string while the method return value is an integer.
Next: break and continue statements >>
More C# Articles
More By Michael Youssef