Defining variables


I anticipated what we gonna do as an exercise and declare variables before it asked. I even didnt think about it before and somewhat fast-forwarding the video then i noticed variables are defined in Start method in video but i defined them in class itself. Which is better practice or what are downsides/upsides of defining them in class/method ?


If a variable is declared within a method, then it can only be accessed within the method. Generally, you should always try to do this if you can. It prevents any outside methods from messing with that variable and prevents any naming conflicts. Also, methods declared locally take priority over methods declared in a class if there is a conflict.

An important detail, however, is that the variable declared within a method will be gone once the method has stopped running. So it’s good for temporary data that the method needs to make calculations and stuff.

Variables declared outside of a method are declared within the class. That means any method within the class has access to read and modify the variable. As long as the class is around, it will remember the variable and the data it contains. However, the class-declared variable will be ignored if the method has a locally-declared variable with the same name.

As a general rule, you should always declare your variables locally (within the method you need them) unless:

  1. you need it accessed by more than one method,
  2. you’ll still need the variable after the method is run, or
  3. you need to serialize it.


It’s worth noting in addition to Anthony’s reply, and I’m sure they’ll cover this later, that you can always access fields that share a local variable name with ‘this.’. If you declared int max at class scope and you had a max declared at method scope as well, this.max would access the field and max would access the local variable.

A good convention to avoid the dilemma outright is to prefix fields with something along the lines of _ or m_. for example _max as opposed to max. PascalCase properties/methods. camelCase local variables. Keeps things organized and you don’t have to worry about naming a variable something that doesn’t make as much since just to avoid conflict.

Don’t feel bad, I’m a few minutes from the end of that lesson and I declared mine “private int _guess, _minimum, _maximum;” at the same scope. Figured I’d need them again.


This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.