Dim vs Private/Public

前端 未结 2 787
甜味超标
甜味超标 2021-01-05 16:20

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

2条回答
  •  礼貌的吻别
    2021-01-05 17:13

    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]

提交回复
热议问题