Form Level Scope

rocky050371 used Ask the Experts™
When declaring / launching a new form a menu item, should the variable be set to module level rather than procedure, what is the best practice.

        _form = New ListForm()

or dim frm as form = new ListForm


Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Éric MoreauSenior .Net Consultant
Top Expert 2016

if you do not need the reference to your _form from elsewhere then in the procedure, declare it local to the procedure
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

It might be useful to declare it at the form/class level if you want to keep an easy reference so you can allow only one instance of the form to be opened at any one time.

*They are others ways of doing this as well.

Top Expert 2015
The principle is very simple and applies to all your variables, not only forms. Use the first of the following rules that apply to your condition, in order:


If a variable is used only in a block (If..End If / For...Next), declare it in the block (block variable).


If a variable is used only in the procedure, declare it the procedure (local variable).


If a variable is used only in the procedure but needs to keep its value between calls to that procedure, declare it in the procedure and replace Dim by Static (static variable).


If a variable is used in many procedures in the same form / class / module, declare it with Dim or Private at the "module level" (private member).


If a variable is used in many forms / classes / modules, declare it as Public in one of the form / class / module that is visible by the ones that need it (public member)


Except for very special purposes, mainly for debugging, never declare a variable as Public in a module (global or public variable). These variables use up memory and can be a pain to debug. There are almost always better ways to do things, such as step 5.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial