One use a single-use temporary variable

coding-standardslanguage-agnosticprogramming-languages

Let's say we have a class called 'Automobile' and we have an instance of that class called 'myCar'. I would like to ask why do we need to put the values that our methods return in a variable? Why don't we just call the method?

For example, why should one write:

string message = myCar.SpeedMessage();
Console.WriteLine(message);

instead of:

Console.WriteLine(myCar.SpeedMessage());

Best Answer

Short answer: We don't. Both examples are absolutely fine.

There are three reasons why people use temporary variables anyway (like in your first example):

  1. It gives an explicit name to the intermediate value (we now know that it's a message, not just any old string).
  2. It helps prevent statements getting too long and too complex.
  3. It makes step-debugging easier, because you can step over each part individually (although there are step debuggers that work at sub-line precision).
Related Topic