Methods Return Values in C#
Learn how methods return values using the return keyword with practical C# examples.
Table of Contents
- What is a Return Value?
- Why Return Values?
- Syntax
- Examples
- Common Mistakes
- Best Practices
- Summary
What is a Return Value?
A return value is the result that a method sends back to the code that called it. The return keyword ends the method execution and returns a value.
Note: A method with a return type must always return a value of the correct type.
Method Syntax
returnType MethodName(parameters)
{
return value;
}
Method Returning an Integer
static int Add(int a, int b)
{
return a + b;
}
int result = Add(10, 20);
Console.WriteLine(result);
Method Returning a String
static string GetMessage()
{
return "Welcome to C#";
}
Console.WriteLine(GetMessage());
Method Returning a Boolean
static bool IsAdult(int age)
{
return age >= 18;
}
Console.WriteLine(IsAdult(25));
Using Returned Values
int total = Add(15,25);
if(total > 30)
{
Console.WriteLine("Total is greater than 30");
}
Tip: Return values make methods reusable because the caller decides how to use the returned data.
Complete Example
using System;
class Program
{
static double CalculateArea(double radius)
{
return 3.14 * radius * radius;
}
static void Main()
{
double area = CalculateArea(5);
Console.WriteLine("Area = " + area);
}
}
Output
Area = 78.5
Common Mistake: Don't forget to return a value from methods whose return type is not
void.void vs Return Value
| void Method | Method with Return Value |
|---|---|
| Does not return any value. | Returns a value to the caller. |
| Used for actions like printing. | Used for calculations and results. |
Best Practices
- Return meaningful values.
- Keep methods focused on one task.
- Use the correct return type.
- Avoid unreachable code after
return.
Summary
| Concept | Description |
|---|---|
| return | Ends a method and returns a value. |
| void | No value returned. |
| Return Type | Specifies the type of returned value. |
Interview Questions
- What is a return value?
- Difference between void and int methods?
- Can a method return a string?
- What happens if a non-void method doesn't return a value?
Practice Exercise
- Create a method that returns the square of a number.
- Create a method returning the maximum of two numbers.
- Create a method returning true if a number is even.
FAQ
Can a method return different data types?
Each method returns only one declared return type, but you can create different methods with different return types.
Next Tutorial: Recursion in C#
No comments:
Post a Comment