user1320370
user1320370

Reputation: 95

vb.net create a reference to an object

I need to create a reference to object, where Prog2 is a reference to Prog1 Here what I need:

dim Prog1 as myclassprogressbar
dim Prog2 as myclassprogressbar

Prog1.initialize()
Prog1.max=10
Prog1.min=1
Prog1.value=5

Prog2.initialize()
Prog2.max=10000
Prog2.min=100
Prog2.value=500


Prog2=Prog1

Prog1.value=7


debug.print Prog2.value

7

Is possible create a reference to an object like this code ?

Upvotes: 0

Views: 2102

Answers (1)

selfstudy
selfstudy

Reputation: 523

You need to instantiate the class using New. Then assuming myclassprogressbar is a class, since classes are reference type, after you assign Prog2 = Prog1, the variable Prog2 will point to the same object which Prog1 is pointing to.

So if you assign something to Prog1.Value, then since Prog2 is pointing to the same object, then Prog2.Value will be the same value as Prog1.Value.

After you define Prog1 and Prog2, each of the variables are pointing to different objects in memory:

Variable         | Memory
---------------------------------------------------
Prog1        --> | [Min:1     Max:10     Value:5  ]
Prog2        --> | [Min:100   Max:1000   Value:500]

After you set Prog2 = Prog1, then both of them are pointing to the same object in memory and the only thing that happens to the object that you had assigned to Prog2 is, the object is still in memory, you just lost the reference to that object:

Variable         | Memory
---------------------------------------------------
Prog1, Prog2 --> | [Min:1     Max:10     Value:5  ]
                 | [Min:100   Max:1000   Value:500]

So, if you set Prog1.Value = 7 or Prog2.Value = 7, the result is the same:

Variable         | Memory
---------------------------------------------------
Prog1, Prog2 --> | [Min:1     Max:10     Value:7  ]
                 | [Min:100   Max:1000   Value:500]

You can learn more about Value Types and Reference Types.

Upvotes: 3

Related Questions