Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always best practice to declare a variable?

I'm new to C# and any form of programming, and I have a question that seems to divide those in the know in my university faculty. That question is simply: do I always have to declare a variable? As a basic example of what I'm talking about: If I have int pounds and int pence do I need to declare int money into which to put the answer or is it ok to just have:

textbox1.Text = (pounds + pence).ToString(); 

I know both work but i'm thinking in terms of best practice.

Thanks in advance.

like image 297
Dylan Jackson Avatar asked Apr 25 '11 14:04

Dylan Jackson


People also ask

Should I always declare variables?

In JavaScript, one should declare all variables at the beginning of the function to mitigate the risk of mistakes related to the fact that the scope of variables is a function.

Why it is important to declare a variable?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.

What is the rule of declaring variable?

Rules for defining variablesA variable can have alphabets, digits, and underscore. A variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc.


1 Answers

In my opinion the answer is "no". You should, however, use variables in some cases:

  • Whenever a value is used multiple times
  • When a call to an expensive function is done, or one that has side-effects
  • When the expression needs to be made more self-explaining, variable (with meaningful names) do help

Basically, follow your common sense. The code should be self-explaining and clear, if introducing variables helps with that then use them.

like image 188
Lucero Avatar answered Sep 19 '22 23:09

Lucero