It's easy to understand why method()
returns a value - but I can't wrap my head around the concept of a method that doesn't return a value.
static void PrintName(string firstName, string lastName)
{
Console.Writeline($"{firstName} {lastName}");
}
This method prints firstName
and lastName
to the console, but doesn't return a value. Why would a programmer do that? How is it used?
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 GetDate() { 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)