1

I have been charged with porting a VB6 project into VB.NET. In vb6, if you were in a class separate to a particular variable, you could access that variable easily:

Public Class Foo
    Public k As Integer
End Class

Public Class Bar
    k = 12
End Class

In VB.NET, my understanding is that before you can use a variable in another class, you must declare a new instance of it:

Dim foobar As New Foo

This would be fine, but I have to access these variables from different classes and every time I declare a new instance, it wipes all old values from the variables, which I need. Can anybody help? I tried using Inherits statements but they presented many problems.

Thanks. Nick

Nick
  • 147
  • 1
  • 5
  • 16
  • As I remember that isnt possible in Vb6 unless you mean module? – JonAlb Oct 31 '11 at 09:56
  • I did mean module, apologies. I'm in VB.NET mode! – Nick Oct 31 '11 at 09:58
  • 1
    Well in that case you can use Public Module Foo in your vb.net code for the port and it will work just fine. However once you have a ported system I would recommend a refactor and changing the architecture, having variables accessible from anywhere will cause spaghetti code and a maintenance nightmare. – JonAlb Oct 31 '11 at 10:13

3 Answers3

6

Your're looking for the shared keyword. This makes the member available to other classes without having to have an instance of your class. See MSDN for more info

flipchart
  • 6,548
  • 4
  • 28
  • 53
  • Thank you, I have implemented that and now all variables in my inventively named "variable.vb" class are Public Shared. However, in my main calculation class every variable name must be preceded with "Variable.", so a variable must be referenced with "Variable.xxxx". Is there a way to get round this, too? – Nick Oct 31 '11 at 09:45
  • 1
    Not 100% sure, but you may be able to use the `with` statement: http://msdn.microsoft.com/en-us/library/wc500chb.aspx See this post for usage: http://stackoverflow.com/questions/283749/the-vb-net-with-statement-embrace-or-avoid – flipchart Oct 31 '11 at 09:48
  • 1
    @Nick - Yes just add `Imports [ProjectName].[ClassName]` at the top of the page – Matt Wilko Oct 31 '11 at 09:49
2

For the port just use Public module like you would in vb6

Public Module Foo
   Public k As Integer
End Module

Public Module Bar
   Foo.k = 12
End Module

Its not good practice but it will help you do your first pass at the port. Ideally you would refactor out modules/shared functions as being able to access variable from any part in the system will produce code that is harder to maintain

JonAlb
  • 1,702
  • 10
  • 14
0
Dim YourobjName As YourClassName = Me.DataContext

Now you can use public methods and functions with YourobjName. Here YourClassName will be the class you want to access the public objects.

Milan Sheth
  • 884
  • 12
  • 11