It is easy to understand why a method() returns a value. But how to wrap my head around the concept of a method that is not supposed to return a value?
static void PrintName(string firstName, string lastName)
{
Console.Writeline($"{firstName} {lastName});
}
This method above outputs firstName and lastName, and does not return a value. Why a programmer would decide to not return a value? How is it used then?
>Solution :
Think of methods that return a value as if they’re an answer to a question:
Q: What’s today’s date?
A: April 15, 2022.
public string GetTime() { return DateTime.Now.ToShortDateString(); }
Think of methods that don’t return a value as an action executed based on a request.
Person 1: Please put this mug on the table.
Person 2: *puts the mug on the table* – doesn’t need to say anything
public void PutMugOnTheTable(Mug mug) { Table.Items.Add(mug); }
See also this related post on Software Engineering SE:
When and why you should use void (instead of e.g. bool/int)