Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use the return statement in C#?
The return statement in C# is used to exit a method and optionally return a value to the caller. When a method contains a return statement, the program control immediately transfers back to the calling method along with the specified return value.
Syntax
Following is the syntax for using the return statement −
return; // For void methods (no value returned)
return expression; // For methods that return a value
Using Return Statement with Value Types
When a method has a return type other than void, it must return a value of that type. Here's an example that calculates the factorial of a number −
using System;
class Factorial {
public int CalculateFactorial(int n) {
int result = 1;
while (n != 1) {
result = result * n;
n = n - 1;
}
return result;
}
static void Main(string[] args) {
int value = 5;
Factorial fact = new Factorial();
int factorial = fact.CalculateFactorial(value);
Console.WriteLine("Factorial of {0} is: {1}", value, factorial);
}
}
The output of the above code is −
Factorial of 5 is: 120
Using Return Statement in Void Methods
In void methods, the return statement is used to exit the method early without returning any value −
using System;
class Calculator {
public void CheckNumber(int number) {
if (number
The output of the above code is −
Negative number detected. Exiting method.
Processing positive number: 4
Square: 16
Multiple Return Statements
A method can have multiple return statements, but only one will execute during any single method call −
using System;
class MathOperations {
public string CompareNumbers(int a, int b) {
if (a > b) {
return "First number is greater";
}
else if (a
The output of the above code is −
First number is greater
Second number is greater
Both numbers are equal
Key Rules
-
Methods with a return type other than
voidmust return a value of the specified type. -
Once a
returnstatement executes, the method immediately exits ? no code after the return statement will execute. -
In
voidmethods,returnis optional and used only for early exit. -
A method can have multiple
returnstatements, but only one executes per method call.
Conclusion
The return statement in C# is essential for transferring control back to the calling method and optionally passing back a result. It enables methods to produce outputs, exit early when needed, and maintain clean program flow through proper value exchange between different parts of your code.
