The return statement is used to exit a method and return a value to the caller. When a method reaches a return statement, the execution of the method terminates immediately, and the specified value (if any) is sent back to the calling code.
Here's how you can use the return statement:
public int Add(int a, int b)
{
int sum = a + b;
return sum;
}
In this example, the Add method takes two integer parameters a and b, calculates their sum, and returns the result using the return statement.
You can also use the return statement to exit a method without returning any value (for methods with a return type of void):
public void DisplayMessage()
{
Console.WriteLine("Hello, world!");
return; // This is optional for void methods but can be used for early exit if needed.
}
The return statement is particularly useful in functions that perform calculations or processes and need to provide a result back to the calling code. Additionally, it allows you to exit the method early if certain conditions are met without executing the remaining code in the method.