0
0
C Sharp (C#)programming~5 mins

Return values and void methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Return values let methods send back results to where they were called. Void methods do something but don't send anything back.

When you want a method to calculate and give back a number or text.
When you want a method to perform an action like printing or changing something without giving back a result.
When you want to reuse a method's result in other parts of your program.
When you want to organize your code by separating tasks that produce results from tasks that just do work.
Syntax
C Sharp (C#)
returnType MethodName(parameters) {
    // code
    return value; // only if returnType is not void
}

void MethodName(parameters) {
    // code
    // no return value
}

The return keyword sends a value back from the method.

Methods with void do not return anything and do not use return with a value.

Examples
This method adds two numbers and returns the sum.
C Sharp (C#)
int Add(int a, int b) {
    return a + b;
}
This method prints a message but does not return anything.
C Sharp (C#)
void PrintHello() {
    Console.WriteLine("Hello!");
}
This method returns a greeting message using the given name.
C Sharp (C#)
string GetGreeting(string name) {
    return $"Hello, {name}!";
}
Sample Program

This program has a method Multiply that returns the product of two numbers. The ShowResult method prints the result but returns nothing. The Main method calls both to show how return values and void methods work together.

C Sharp (C#)
using System;

class Program {
    static int Multiply(int x, int y) {
        return x * y;
    }

    static void ShowResult(int result) {
        Console.WriteLine($"The result is {result}");
    }

    static void Main() {
        int product = Multiply(4, 5);
        ShowResult(product);
    }
}
OutputSuccess
Important Notes

Use return values when you need to use the result later.

Void methods are good for actions like printing or changing data without needing to send anything back.

Once a method hits a return statement, it stops running.

Summary

Return values send data back from methods.

Void methods do not send data back.

Use return values to get results; use void for actions only.