How to reference a class variable from another class in vb.net

user1839684 picture user1839684 · Nov 20, 2012 · Viewed 9.1k times · Source

I have the following (simplified to make this easy to read)

first class:

Class MainWindow
     Private mFile As myFile 'myFile is a class containing a bunch of stuff

     Sub go()
          dim editFiles as New EditFiles(mFile)
     End Sub
End Class

Second Class:

Public Class EditFiles
    Private mFile As myFile 'myFile is a class containing a bunch of stuff
Sub New(ByRef passedFile As myFile)

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    mFile = passedFile

End Sub

what I would like to happen is any changes I make to mFile in the second class to also change mFile in the first class, I thought that by passing it ByRef in the initialization that would happen but apparently not.

What I am wondering is what is the appropriate method to make this work? I know I could create a global variable but there must be a way to pass the pointer of mFile from the first class so that mFile in the second class is essentially the same.

If you could show me a simple example perhaps by editing the above code I would really appreciated it!

Answer

Austin Davis picture Austin Davis · Nov 20, 2012

You should create an object of the first class in the second class. Also you need a method that changes the value of mFile in the first class. It should be something like the following.

Class MainWindow
     Private  mFile As myFile 'myFile is a class containing a bunch of stuff

     Sub go()
          dim editFiles as New EditFiles(mFile)

     End Sub

     sub setMFile(_mfile as myfile)
        me.mfile = _mfile
End Class

Second class

Public Class EditFiles
    Private mFile As myFile 'myFile is a class containing a bunch of stuff
    Sub New(ByRef passedFile As myFile)

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    mFile = passedFile
    dim newObject as new MainWindow
    newobject.setMFile(mFile)
End Sub