At the head of a module, I wish to declare some global variables for use in various subs/functions.
What is the difference between
Dim x as string
and Private x as string
/ Public x as string
, and when would I use one over the other?
At the head of a module, I wish to declare some global variables for use in various subs/functions.
What is the difference between
Dim x as string
and Private x as string
/ Public x as string
, and when would I use one over the other?
Private and public control the scope of the variable or object you're declaring.
Private
will only allow members of the relative module/class/whatever to access the instancepublic
will allow anything in the same scope as the module/class/whatever to access it.Dim
defaults to either public or private, depending on what you're working in. A class for example, will default to private. I suggest reading up on encapsulation and OOP to get a better feel for this.They are different, but related, things.
Dim Statement (Visual Basic) [MSDN] tells us:
and
Access Levels in Visual Basic [MSDN] tells us:
and
so
Private x As String
is the equivalent ofDim Private x As String
(although if you type this Visual Studio will remove the Dim)and
Dim x As String
is equivalent toPrivate x As String
except in Structures (where it is equivalent toPublic x As String
) and interfaces where declaring variables is not allowed - see Declaration Contexts and Default Access Levels (Visual Basic) [MSDN]