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 toPrivate/Public/etc.Sharedmeans “specific to the type, not to any instance of the type”. YourSharedfunction can’t useWCbecause it doesn’t have an instance ofxTestto find the specificWCvariable for. Imagine it was anamevariable instead – it’s like asking aPersonclass “What’s your name?” when instead each individualPersoninstance has a name.You should think carefully for each member (whether it’s a function or a variable) whether it’s logically
Sharedor 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
WebClientas a field in the first place.WebClientis designed to be created, used, then discarded. I’d also suggest changing your names to follow .NET naming conventions.)