Return values are an essential concept in C# programming. They allow methods to send data back to the caller, enabling efficient data flow and modular code design.
In C#, a return value is the data that a method sends back when it completes its execution. This mechanism is crucial for retrieving results from method calls and passing information between different parts of your program.
To specify a return value, use the return
keyword followed by the value or expression you want to return. The method's return type must match the type of the returned value.
public int Add(int a, int b)
{
return a + b;
}
In this example, the Add
method returns an integer value, which is the sum of its parameters.
Methods that don't return a value are declared with the void
keyword. These methods perform actions without sending data back to the caller.
public void PrintMessage(string message)
{
Console.WriteLine(message);
}
A method can have multiple return statements, but only one will be executed. This is useful for conditional logic within methods.
public string GetGrade(int score)
{
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}
C# methods can return any data type, including custom classes, structs, or collections. This allows for returning complex data structures.
public List<int> GetEvenNumbers(int max)
{
var evenNumbers = new List<int>();
for (int i = 2; i <= max; i += 2)
{
evenNumbers.Add(i);
}
return evenNumbers;
}
TryParse
pattern.To deepen your understanding of C# methods and return values, explore these related topics:
Mastering return values is crucial for writing efficient and modular C# code. Practice implementing various return types and scenarios to solidify your understanding of this fundamental concept.