I am trying to use a privately declared variable/object within a class, from a shared function within that same class.
My main goal is to be able to access the shared function outside of the class, but not the variables, seeing as they are private. I do not think setting all variable/object declarations as "shared" would be an elegant solution.
Here is a snippet for better examination:
Module main
Sub Main()
MsgBox(xTest.xMain)
End Sub
End Module
Class xTest
Private WC As New Net.WebClient()
Shared Function xMain() As String
Return WC.DownloadString("http://example.com")
End Function
End Class
How would I go about doing this, properly of course.
I suspect you're confused about the meaning of Shared
. This is orthogonal to Private
/Public
/etc.
Shared
means "specific to the type, not to any instance of the type". Your Shared
function can't use WC
because it doesn't have an instance of xTest
to find the specific WC
variable for. Imagine it was a name
variable instead - it's like asking a Person
class "What's your name?" when instead each individual Person
instance has a name.
You should think carefully for each member (whether it's a function or a variable) whether it's logically Shared
or not.
See the MSDN page on shared members for more details - although I dislike the description used there. "... shared by all instances of a class ..." sounds like there has to be an instance in the first place. There doesn't - it's just that the member is associated with the type itself. A shared variable can be used even if no instances of the class are ever created.
(As an aside, I probably wouldn't keep hold of a WebClient
as a field in the first place. WebClient
is designed to be created, used, then discarded. I'd also suggest changing your names to follow .NET naming conventions.)