Search code examples
vb.netbyref

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


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!


Solution

  • Here is how I ended up solving my problem:

     Class MainWindow
     Private  mFile As myFile 'myFile is a class containing a bunch of stuff
    
     Sub go()
          dim editFiles as New EditFiles(me, mFile)
     End Sub
    
     sub setMFile(_mfile as myfile)
        me.mfile = _mfile
     End Class
    

    Second class

    Public Class EditFiles
    Private mainWindow As mainWindow
    Private mFile as myFile
    Sub New(ByVal sourceWindow As mainWindow, byVal sourceFile as myFile)
    
         ' This call is required by the designer.
        InitializeComponent()
    
        ' Add any initialization after the InitializeComponent() call.
        mainWindow = sourceWindow
        mFile = sourceFile
    
    end Sub
    Sub setFile
        mainWindow.setMFile(mFile)
    End Sub