Global Variable in Class

  • Thread starter Joe via DotNetMonster.com
  • Start date
J

Joe via DotNetMonster.com

Hi,

How can I declare a variable in a Class so that it can be accessed from the
page that calls it? Normally I would declare a variable outside a function
so that it can be used globally on the page but I'm not sure how to do it
in a Class. I tried using public but that didn't work. I have the following:

Public Class dataClass
Public Shared Function GetRep(ByVal prodNumber As Integer) As
DataSet
Dim ProdName as String

I tried Public ProdName as String but got an error.

Thanks
 
J

Joshua Flanagan

Shared functions can only only access Shared class variables. If you
need GetRep to be Shared, and you need to use ProdName within GetRep,
you must declare GetRep as Shared.

Keep in mind, when you use Shared class level variables in a
multi-threaded environment (like ASP.NET), you need to be careful that
you only use the variable in a thread-safe way (look at the
documentation for the SyncLock keyword for a start).

Joshua Flanagan
http://flimflan.com/blog
 
J

Joe via DotNetMonster.com

Thanks for the reply. I have declared the function as shared. How would I
define the variable within the function?
 
J

Joshua Flanagan

Now I'm confused. Do you want the variable to be in the function (no
data is saved across function calls), or do you want the variable
outside of the function (dad is saved across function calls)?

If you want the variable inside the function, just declare it in the
function:

Public Class dataClass
Public Shared Function GetRep(ByVal prodNumber As Integer) As DataSet
Dim ProdName as String
'do stuff with ProdName - value is lost at end of function
End Function
End Class

If you want the variable outside the function, just declare it outside
of the function (but make sure to add the Shared modifier so it is
available to Shared functions):


Public Class dataClass
Private Shared ProdName as String
Public Shared Function GetRep(ByVal prodNumber As Integer) As DataSet
'do stuff with ProdName
' value is still available after function
End Function
End Class
 

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

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top