How do I decide what a function should return?
Quick answer
Return a value when the caller needs one result to use or inspect. Return several related values when they form one coherent result; in C#, a named tuple is one option. Use void when the function’s purpose is to perform work and the caller does not need a result. Ask what the caller needs next, and avoid returning unrelated items together just to reduce the number of functions.
The question, the details, the next step.
A practical checklist
Write down what the caller needs to do immediately after calling the method.
Return one value if there is one clear result the caller needs.
Consider a named tuple only when the returned values are related and useful together.
Use
voidif the method performs an action and the caller needs no result.Check that names and the call site make each returned value understandable.
Reconsider the design if the method returns unrelated values or repeats information the caller already has.
A few more useful answers
Is returning a tuple always better than creating a separate type?
No. C# supports returning related values as tuples, but that does not make tuples the right choice for every design. Consider whether the result needs a more descriptive structure, and keep the decision focused on what the caller needs.
Can a `void` method stop before reaching its end?
Yes. In C#, a void method can use a bare return to stop execution. That ends the method without returning a value. [S1]
What if the method has an action and a useful result?
Make the caller’s needed result explicit and decide whether it belongs with the action’s outcome. The language’s available return forms do not, by themselves, determine the right design for a particular method.
Sources
References used for this guide.
- [S1] Overview of methods — C# | Microsoft Learn learn.microsoft.com · Checked
