Home > database >  Why would a C# method not return a value?
Why would a C# method not return a value?

Time:04-15

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?

CodePudding user response:

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)

CodePudding user response:

According to the name, there is no reason to return the value. If you create or build something, you can expect results, but it is difficult to expect results for internal operations such as Add, Remove, Print, etc.

CodePudding user response:

There are plenty of reasons to not return a value. Your example is a very good one. What possible information would you want to have returned from that method? It's a self-contained function that doesn't manipulate any data or affect the state of the program. Return values are used to pass back results of operations, statuses, modified data, etc. For situations in which you don't need anything back there's void.

Now you might think that you'd rather have PrintName return a boolean for success, but the method as written is just going to work. Putting in a return statement and consuming the returned value is added code complexity for no benefit.

  • Related