Ant, there's no reason not to be pedantic; these things matter.
Many people believe that variables should be declared at the top of the
scope they need to be visible in.
The compiler doesn't care where they lie, but for visual scans of the code
it seems to help if they're all grouped together at some predictable place
in the code. Encourages you to use some sort of structured commentary
describing them, lets you see them all in a glance, etc. The more visual
structure you apply to your coding style, in fact, the easier it is for a
reader to use our human pattern-matching abilities to extract information
from the source code. And as we all know, it's much harder to read code than
it is to write it.
Many people also believe that you should declare a variable within the
narrowest scope that it's needed in. So variables declared at the very top
of a method are those that are used throughout the method, those that are
used in inner blocks should be declared at the top of their blocks, and so
forth. One good reason for keeping tight scope on variables is that if an
inner block never gets executed on account of a branch condition, the
runtime never needs to exert itself to instantiate it.
C# is highly block-scoped; VB didn't used to be, but now is.
Iteration variables are best declared, according to Microsoft, in the top of
the iteration:
foreach (string s in substrings) ;
for (int i = 0; i <= something; i++) ;
Or if you like VB.Net:
For Each s As String In substrings
For i As Integer = 0 To something
Naturally, I concur with these opinions, after about a million years in this
biz, or I wouldn't be spreading them around.
In practice, of course, I sometimes bend these rules and plunk down a
declaration in medias res, but I always feel a teensy bit uncomfortable when
I do it. And sometimes I go back and move them. But not always.
HTH,
Tom Dacon
Dacon Software Consulting
"Ant" <An*@discussions.microsoft.com> wrote in message
news:CA**********************************@microsof t.com...
hi,
I'm now using C#. Seeing as though you can declare & initialize or pass a
value to a variable on the same line as the declaration, is it still best
practice to group all the variables together at the top of the method, or
is
it now acceptable for them to be declared at the point where they are
initially needed, seeing as though you can 'go to the definition', with
the
right click of a mouse?
Pedantic I know, but I'm curious.
thanks for your opinions
Ant