Return
Lesson 13Author : Afrixi
Last Updated : February, 2023
In C#, a method can return a value using the return
keyword. When a method returns a value, it must have a return type specified in its declaration. Here is an example of a method that returns an integer value:
public static int Add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
In this example, we’ve declared a method called Add
that takes two integer parameters, num1
and num2
. The method calculates the sum of the two parameters and stores the result in a variable called sum
. The method then returns the value of sum using the return keyword.
We can call this method from elsewhere in our code and use the returned value. Here’s an example:
int result = Add(5, 7);
Console.WriteLine(result); // Output: 12
In this example, we’re calling the Add method with the arguments 5 and 7. The method returns the sum of these two values, which is 12. We’re then assigning the returned value to a variable called result
, and finally printing the value of result to the console.
Methods can return values of any data type, including integers, floating-point numbers, Booleans, characters, strings, and even complex objects. Here’s an example of a method that returns a string value:
public static string Greet(string name)
{
return "Hello, " + name + "!";
}
In this example, we’ve declared a method called Greet
that takes a string parameter called name
. The method concatenates the name
parameter with the string “Hello, " and the string “!”, and returns the resulting string.
We can call this method from elsewhere in our code and use the returned value. Here’s an example:
string message = Greet("John");
Console.WriteLine(message); // Output: "Hello, John!"
In this example, we’re calling the Greet
method with the argument "John"
. The method returns the string “Hello, John!”, which is assigned to a variable called message
. Finally, we print the value of message
to the console.