Why do most of the VB.Net examples, define and assign a variable in a single line as it is being used in the program.
In VBA I found it easier to read the code with the variables defined at the top of the function or subroutine.
What do most of you do when defining variables ???
I find the VB.net lines below more difficult to read ..............
For Each acSSObj As SelectedObject In acSSet
Dim acEnt As Entity = acTrans.GetObject(acSSObj.ObjectId,OpenMode.ForWri
Not only VB.NET, but also all languages in .NET such as C#, we need to declare variables as close to where they used as possible, to keep the scope of those variables tight, then the optimizer will work better.
Especially in AutoCAD .NET API, we need to use Transaction to wrap the code to clear unmanaged-code memory after using, so keep defining and assigning a variable in a single line as much as possible.
Sometimes its a good idea, sometimes it doesn't matter so much. For casual code there won't be much difference in optimized code. If the variable is used over much of the scope then yes, I do put it at the top; if its use is more restricted I tend to do it closer to where its used so less hunting is required. The important thing is consistency in style so its easy to follow.
Keep in mind those examples are procedural in nature, not necessarily coding style. Scattering the relevant pieces to the four coding winds makes the example difficult to follow.
One thing to watch out for is the default value when you declare the variable, especially with objects. You may end up with a null or other inappropriate value when its used later in the code. Loops can also be a bit tricky - "new"ing a variable inside each cycle may be inefficient compared to doing it just prior to the loop then reseting or assigning values in each cycle.
You might want to consider declaring variables where they're used.
My guess about why you see a lot of VB.NET code that does that, is because much of it was originally written in C# and then translated to VB.NET. One key difference between C# and all VB and VBA variants is that variable scope can be explicitly defined in C# (using curly braces), whereas variable scope in VB is the entire body of the sub or function containing the variable, from the point where it is declared to the end of the function/sub. Many code translators will deal with that difference by renaming variables in cases where the same identifier is used in two different scopes that are not nested in each other. While that's perfectly fine in C#, it isn't in VB so code translators try to deal with it by renaming one of the variables.
Access a broad range of knowledge to help get the most out of your products and services.