Shared Variables and Methods

Shared Variables and Methods

Shared variables or methods provide easy access to processes and values without the need to create an instance of the class.

A shared variable or a shared method has two distinctive  features:
1. The same variable or method is being referred to by all code that uses the  shared variable or method, and
2. You do not need to have an instance of the class in order to use a shared  variable or method.

Shared methods and variables can be thought of as belonging to  the Class, not to an instance of the Class.

An example of a shared object in the .Net Framework (there  are many of them) is Now.  The Now expression could be returned by code  such as this:

 '1 
 MsgBox(Now)
 '2
 MsgBox(DateTime.Now)
 '3
 Dim DT As DateTime = New DateTime
 MsgBox(DT.Now)

The third usage throws the error “Access of shared member,  constant member, enum member or nested type through an instance; qualifying  expression will not be evaluated.”.  That means that the result of the  expression will not be the Now property of the DT object – the DT object will  not be ‘evaluated’. The message is a warning that, even though the syntax is  legal, the code does not make any sense, because Now is not a property of an  instance of the class – it is a property of the class, and should not be  referred to by using the instance variable.

The first two forms of code (which are equivalent) return the (shared) Now property of the class, not of any class instance.

Now is a property of the class, but the exact same conditions apply to a method of the class. The Split Method of the String class is a good  example of a shared method.

A shared variable or method is declared using the Shared  keyword, eg:

  PublicShared ReadOnlyProperty Now As DateTime

A Public Shared property or variable can be used as a global  variable.  Because it is a property or variable of a class (not an  instance) there can only be one copy of it throughout an application, so it will  have the same value wherever it is used.

Note: The above description has referred to  shared variables and methods (Subs and Functions).  Shared can also be used  with Operators, Properties, and Events, for the equivalent effect.

Note: The equivalent functionality in C# is  referred to as Static.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s