Course Content
C# Basics
C# Basics
Method Return Values
In the last two chapters, we learned how to pass data into the functions but now we will learn how to retrieve data from the method back to the place where it was executed.
The process of retrieving data from methods is also called returning data and the data or value which is returned is called the return value.
The syntax for creating a method with a return value is the following:
main
// Note: Parameters are optional static returnDataType methodName(dataType parameter1, ...) { return valueToReturn; }
The valueToReturn
represents a variable, value, or expression which must be of the same type as the returnDataType
. Following is the correct example:
main
static int sumOfThree(int a, int b, int c) { int sum = a + b + c; return sum; }
If the wrong type of data is returned, it will show an error:
main
static int sumOfThree(int a, int b, int c) { string sum = "10"; return sum; // Error (the string has a number in it, but it is still a string/text) }
The value which is returned from the sumOfThree
method can be stored into a variable:
main
using System; namespace ConsoleApp { internal class Program { static int sumOfThree(int a, int b, int c) { int sum = a + b + c; return sum; } static void Main(string[] args) { int result = sumOfThree(5, 10, 15); Console.WriteLine(result); // Output: 30 } } }
We can also directly output the return value using Console.WriteLine
:
main
using System; namespace ConsoleApp { internal class Program { static int sumOfThree(int a, int b, int c) { int sum = a + b + c; return sum; } static void Main(string[] args) { Console.WriteLine(sumOfThree(5, 10, 15)); } } }
We can also directly write expressions as return values. In that case, the expression is first evaluated and then the resulting value is returned. Following are some examples:
Product of Three Integers:
main
using System; namespace ConsoleApp { internal class Program { static int productOfThree(int a, int b, int c) { return a * b * c; } static void Main(string[] args) { Console.WriteLine(productOfThree(5, 10, 15)); } } }
Average:
main
using System; namespace ConsoleApp { internal class Program { static float average(int a, int b) { return (a + b) / 2.0f; } static void Main(string[] args) { Console.WriteLine(average(5, 10)); } } }
Thanks for your feedback!