C# – Reason Behind Methods with Return Values vs Void Methods

cmethodsprogramming-languages

I want to uderstand why there is a method in C# that could reurn a value, for example:

public int Accelerate()
{
   Speed++;
   return Speed;
}

and a method that does not reurn a value (void)?

What is the difference in the following example of the above one:

public void Accelerate()
{
  Speed++;
  Console.WriteLine(Speed);
}

I see that last one will save us a time rather than defining a variable to hold this field in when creating a new object! I'm beginner, so could anyone explain?

Best Answer

The second one only works within a console based app. It assumes you want to print the speed in a console screen.

The first one will work on a console, or as part os a web app, or as part of a GUI based desktop app, or mobile app.

The first one is therefore more useful as part of a modular system.

The second one is doing a calculation and also printing to screen, mixing the business logic with the presentation, which is bad.

That said, first method shouldn't even return the value. A separate getSpeed() method should exist to return that value. Accelerate should only increment the speed.

Also the variable should be named speed in lowercase and the method whould be called accelerate() also in lowercase.

Related Topic