Shared Variable Question VB.NET 2003

S

Sid Price

I need to have a class variable retain its value between destruction of the
object and the next construction. I have declared the variable:

Public Shared mLastTabID As Int32 = 0
In the "New" method of the class I attempt to access this variable and use
it, however it always has the value "0", even though it is getting set
during the life of the (previous) object.

Is my understanding of shared variable wrong? If so, what is the correct way
to achieve this?

Thank you,

Sid.
 
A

AlanT

From your description your understanding is not wrong.
The shared variable should retain its value across instances.


e.g.

public Class Widget

private shared s_ID as integer = 0

public sub new()
_id = s_ID
s_ID +=1
end sub

Public readonly property MyID as integer
Get
return _id
end get
end property

private _id as integer

end class


s_ID is initialized when the class is initialized
every time you create an instance of Widget we take the current id and
use it for the instance, incrementing it for the next time.
Each instance now has a different id.


The only thing that springs to mind is that you are resetting
mLastTabID to 0 in your code somewhere without realizing it.
Can you post a sample?


hth,
Alan.
 
R

R. MacDonald

Hello, Sid,

I suspect that Alan's point:
The only thing that springs to mind is that you are resetting
mLastTabID to 0 in your code somewhere without realizing it.

must be correct. Something that might make it harder to find where this
is happening is that you have declared the Shared variable to be Public.
It would be more typical to declare this as Private and control any
external access via a Public property, as shown in Alan's example.

Even if it is necessary to keep it as Public, you might be able to
quickly find the source of the problem by temporarily changing the
declaration to Private. All the external references to it will become
immediately obvious via the Task list. (Of course, this requires that
"Option Explicit" is turned on.)

Cheers,
Randy
 
S

Sid Price

Thanks for the pointers, I have resolved the issue. The class that had the
shared variable is derived from "form" and when instantiated I believe that
it runs in a new thread. I found a note somewhere in the docs that said that
shared variables are initialized in each thread! So, I think this was my
problem. I changed my approach to a different method to achieve the goal and
all is well.

Again, thanks for the pointers,
Sid.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top