Best Practice for Global Variables

I'm writing my first VB.NET application. It's a very simple application that only has 1 form.

A variable that I am declaring needs to be used in multiple procedures (2 button events to be exact). Therefore, I know that I need to declare the variable outside of the button procedure so that it is accessible by both procedures. The question is what's the best way:

Option A) Declare the variable within the form class:

Class Form

Dim MyVar

Procedure A

Do Something

End Procedure A

Procedure B

Do Something

End Procedure B
End Class Form

Option B) Declare the variable within a module that is within the same source file as the form class:

Class Form

Procedure A

Do Something

End Procedure A

Procedure B

Do Something

End Procedure B
End Class Form

Module 'This module in the same source file as the Form

Dim MyVar

End Module

Option C) Declare the variable within a seperate module

Class Form

Procedure A

Do Something

End Procedure A

Procedure B

Do Something

End Procedure B
End Class Form

Module 'This module in a seperate source file (module1.vb)

Dim MyVar

End Module

[1391 byte] By [Ryan_Small] at [2008-1-4]
# 1
I think in general the best practice is to give the variable "just enough" scope, so in this case I would declare it as Private or Protected at the Form level. If it genuinely need to be "global" then a seperate module is the way to go.
TaDa at 2007-10-11 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2

So if I understand you correctly, you are suggesting Option A?

-Ryan

Ryan_Small at 2007-10-11 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 3
Yep.
TaDa at 2007-10-11 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 4
Ryan_Small wrote:

So if I understand you correctly, you are suggesting Option A?

-Ryan

Hi,

I would say Option C) myself as that way you can easily see what is "common" to all FORMs etcetera.

So i would use a separate Module file in the Project.

If you create Public variables they are accessable from all FORMs and other CLASSes and ( i think other MODULEs too ), within the same project only, i believe.

If you create PUBLIC SHARED variables you can use them in a CLASS within a VB.NET generated DLL library file and they are then accessible for use in other PROJECTS.

Hope that helps.

Regards,

S_DS

Spidermans_DarkSide-VSIP at 2007-10-11 > top of Msdn Tech,Visual Basic,Visual Basic General...