Wednesday, October 18, 2006

Shared Members

Visual Basic.NET introduces the concept of shared members. Shared members are a way of creating a member (a property, procedure, or field) that is shared among all instances of a class. For example, you could create a property for a database connection string. This will be the same for each class, so you can fill it in for one class and all classes can then see that one property. Shared properties are most often used in inheritance, so that all objects created from derived classes can share the same member across all instances of the class. However, shared members can be used without regard to inheritance.

Imagine that you have an data file or other mechanism for the student data listed earlier, and you want to define a method to be able to find a student, given his name, and return the student object. Rather than the COM model of having a factory to create the object, you could add the Find functionality as a shared method to the student class.
For example:

Public Class Student

Inherits Person

Public Shared Function Find(ByVal studentName As String) _

As Student

Dim Student As New Student()

Dim xmlobj As Xml.XmlElement

‘get the xml object

‘fill in the mName field

‘fill in the mAddress field

Return Student

End Function

End Class




Shared methods are commonly used in the runtime for this ability to create a specific instance of an object, for example System.IO.CreateDirectory() that will create a directory in the file system, and return a DirectoryInfo object. The same System.IO. Directory class also provides a shared method, Move, to rename a directory.