Declaring variables - best practice?

  • Thread starter Thread starter Rob Meade
  • Start date Start date
R

Rob Meade

Hi all,

New to .Net - still finding my feet...quick question...

In one of my functions I have about a dozen variables being declared at the
top - the first thing within the function, about 2 of these may or may not
be used depending on a couple of IF...Then's further down the page...

What I'd like to know is - should I declare ALL of my variables at the top
like this whether they might be used or not - thus keeping them in one easy
to find location for debugging etc etc, or should I declare them just before
I need them, so in my example - maybe something like this :


Dim strString1 as String ' always used
Dim strString2 as String ' always used

If test = true Then

Dim strString3 as String

strString3 = results

End If


Any advice would be appreciated - I'd like to get this correct from the
outset if possible :o)

Thanks in advance for your replies,

Regards

Rob
 
If the variables will ONLY be used INSIDE the if (caps for emphasis),
declare inside the if. No need to have them hanging outside of the scope, or
even instantiated. If you need them outside the if, you will have to declare
outside.

In general, I declare at the top, inside a section well labeled as
declarations. I make an exception for items scoped inside of a smaller
construct (for ... next, if, do, et al).

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
...
If the variables will ONLY be used INSIDE the if (caps for emphasis),
declare inside the if. No need to have them hanging outside of the scope, or
even instantiated. If you need them outside the if, you will have to declare
outside.

In general, I declare at the top, inside a section well labeled as
declarations. I make an exception for items scoped inside of a smaller
construct (for ... next, if, do, et al).

Thanks Gregory, as I suspected but wanted to clarify :o)

Many thanks

Rob
 
Back
Top