6

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?

2

2 Answers 2

13

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 instance

public 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.

4
  • Yes, but what's the difference if you use Dim or not? Mar 6, 2013 at 13:30
  • Please read the answer again. I said dim defaults the scope to public or private depending on whether you're in a structure or class, respectively.
    – MGZero
    Apr 3, 2013 at 1:29
  • Could do with more detail of what dim defaults to
    – mattumotu
    Feb 20, 2017 at 9:50
  • It's stated pretty plainly.
    – MGZero
    Mar 8, 2017 at 3:17
2

They are different, but related, things.

Dim Statement (Visual Basic) [MSDN] tells us:

[Dim] Declares and allocates storage space for one or more variables.

and

The Dim keyword is optional and usually omitted if you specify any of the following modifiers: Public, Protected, Friend, Protected Friend, Private, Shared, Shadows, Static, ReadOnly, or WithEvents.

Access Levels in Visual Basic [MSDN] tells us:

Private (and Public, Protected, Friend, Protected Friend) are Access Modifiers which specify 'what code has permission to read it or write to it.'

and

At the module level, the Dim statement without any access level keywords is equivalent to a Private declaration. However, you might want to use the Private keyword to make your code easier to read and interpret.

so Private x As String is the equivalent of Dim Private x As String (although if you type this Visual Studio will remove the Dim)

and Dim x As String is equivalent to Private x As String except in Structures (where it is equivalent to Public x As String) and interfaces where declaring variables is not allowed - see Declaration Contexts and Default Access Levels (Visual Basic) [MSDN]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.