To allow ALL classes within your program access the variable, you need to make it class-level and define it with Public
and Shared
.
Demonstration:
Public Class MainClass
Public Shared enteredusername As String
Public Shared enteredpassword As String
Private Sub SomeSub()
' Some Code ...
' You can access it here:
enteredusername = "something"
enteredpassword = "something else"
' ... More Code ...
End Sub
End Class
Public Class AnotherClass
'Also, please note, that this class can also be in another file.
Private Sub AnotherSub()
' Some Code ...
' You can also access the variable here, but you need to specify what class it is from, like so:
Console.WriteLine(MainClass.enteredusername)
Console.WriteLine(MainClass.enteredpassword)
' ... More Code ...
End Sub
End Class
Also, on a separate note, the Public
and Shared
modifiers can also be used on methods. If you make a method Private
or don't specify anything, the method will only be accessible from methods in the same class. If you use only Public
, other classes can access the method, but they will need to create a instance of the class, like so:
Dim AC As New AnotherClass
AC.AnotherSub()
If you use both the Public
and the Shared
modifiers, other classes will be able to access the method directly, without creating a new instance. But, you must note, that Shared
methods cannot access non-Shared
methods or variables. Other classes can access Public Shared
methods like so:
AnotherClass.AnotherSub()