Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why would a C# method not return a value?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading