Accessing a Namespace From a Seperate File

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • balabaster
    Recognized Expert Contributor
    • Mar 2007
    • 798

    #16
    Originally posted by mcfly1204
    So basically, the manner in which I would like to use the variable is impossible because that is pretty much the reason for classes. Variables with the same name but that are in different classes are completely different.

    I am going to try a few things, then post what I come up with to get the end results that I want.
    I think you didn't quite interpret my post in the manner I intended. I didn't mean for it to imply you couldn't do what you were attempting - I was highlighting the different declaration types. If you want to reference your variable in a manner such as shared you would declare it as public shared rather than just public...in the same way as you would declare a public shared function/sub.

    File1.vb
    Code:
    Namespace MyNamespace
      Public Class MyDemoClass
        Public Shared MyDataVariable As String
      End Class
    End Namespace
    File2.vb
    Code:
    Imports MyNamespace
    Public Class MyForm
      Public Sub Loaded(ByVal Sender As Object, ByVal e As System.EventArgs) _
      Handles Me.Load
        MyDemoClass.MyDataVariable="Hello World"
        MsgBox MyDemoClass.MyDataVariable
      End Sub
    End Class
    I have to say though, I don't think this is very good coding practice. I'm dubious as to the safety of using this method. The whole concept of object oriented programming is encapsulation and as such a variable or field within that class shouldn't be accessible from other classes except via a property exposing it. A class really has very little business exposing a variable in this manner. This technique should be reserved for calling variables from within modules (which is the technique I demonstrate below)...at least, that's my take on the subject.

    File1.vb
    Code:
    Namespace MyNamespace
        Public Module HelperModule
            Public MyParam As String
        End Module
    End Namespace
    File2.vb
    Code:
    Imports MyNamespace
    Public Class Form1
        Private Sub Loaded(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load
            HelperModule.MyParam = "Hello World"
            MsgBox(HelperModule.MyParam)
        End Sub
    End Class

    Comment

    Working...