Does it even exist? I want to have a shared variable across a module and a class that belong to the same project.
Asked
Active
Viewed 3,597 times
1
-
Declare a variable as Shared. This means it's shared between all instances of the class. [Link to MSDN](http://msdn.microsoft.com/en-us/library/zc2b427x.aspx). – Victor Zakharov Dec 19 '13 at 00:25
-
@Neolisk You cannot declare shared variables in a Module though. – user1676874 Dec 19 '13 at 00:26
-
No, don't use modules. These are something from the old VB6 world. Make a habit to always use classes. If they will contain all shared methods and shared variables - so be it. – Victor Zakharov Dec 19 '13 at 01:57
-
Yeah it wasn't my choice though, and there's not much I can do to avoid it. – user1676874 Dec 19 '13 at 16:40
-
1@Neolisk I disagree. [Modules are not deprecated](https://stackoverflow.com/a/881586/1603095) – NePh Aug 28 '17 at 15:09
-
@NePh: Modules have its use, like extension methods, but most new VB.NET developers tend to use them as global bucket for random stuff. They are not scoped and introduce clutter when misused. Tried to advocate against that. – Victor Zakharov Aug 28 '17 at 15:18
2 Answers
0
you can look into static variables. that's probably the closest thing to shared variables.

Z .
- 12,657
- 1
- 31
- 56
0
Shared
variables exist but you probably mean the old fashioned Global
variables. For that, just declare a variable in an actual module rather than a Class:
Friend Foo As Integer
Public Bar As String = ""
Static vars are quite different

Ňɏssa Pøngjǣrdenlarp
- 38,411
- 12
- 59
- 178
-
While I'm not exactly sure why, just declaring public variables in the Module did actually let me use them in the other classes. Interesting. – user1676874 Dec 19 '13 at 16:42
-
'Friend' will allow the same scope, while 'Public' will make the variables visible outside the assembly. – Ňɏssa Pøngjǣrdenlarp Dec 19 '13 at 16:48
-
Why does it work different from a class though? If I just declare public variables on Class1 I can't see them on Class2 unless I instantiate. – user1676874 Dec 19 '13 at 17:21
-
1**All** class variables require the class to be instanced - thats just how classes work (unless the member is `Shared`). Public vs Friend for them just means whether things outside the class can reference them. For something like the old `Global` variable, you need a Friend or Public variable in a module as in the answer. Usually you can avoid these by using a simple Class as a container, but yes, then that means you need to use them as `If myClass.myVar = "Foo"...` – Ňɏssa Pøngjǣrdenlarp Dec 19 '13 at 17:50