Shared Members

VB .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 also can be used regardless of whether you are using inheritance.

To see how shared properties work, suppose that you wanted to create a logging mechanism to record any kind of message created by the application (informational messages, error messages, and so on). You want to record the message into a log file, and keep a total count of the number of messages, regardless of the type of message.

Start Visual Studio .NET and create a new Windows Application and name it MessageLogTest. Create a new project, but keep it in the same solution. This new project should be a class library, and name it MessageLogger.

In the code for MessageLogger, rename the class Logger, and enter the following code:

Imports System.IO
Public Class Logger
   Public Function LogMsg(ByVal psMessage As String)
      Static iCount As Integer
      iCount += 1
      Dim file As TextWriter = New StreamWriter("c:output.txt", True)
      file.WriteLine(psMessage & ". " & iCount)
      file.Close()
   End Function
End Class

In this application, you are creating one method called LogMsg that accepts a string from the client. The method then has a static integer called iCount. iCount keeps track of the number of messages that the logger has written, and is appended to each message so you can see its value.

Return to the MessageLogTest application. Right-click on the References node in the Solution Explorer window and choose Add Reference. Go to the Project tab and you will see the MessageLogger project. Click the Select button and then click OK. This now adds a reference from the Windows application to the class library you are creating.

On the form, add two buttons. Go to the code window and enter the following code (the Windows Form Designer–generated code is hidden):

Imports MessageLogger
Public Class Form1
   Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

   Dim infoLogger As New MessageLogger.Logger()
   Dim errorLogger As New MessageLogger.Logger()

   Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
      infoLogger.LogMsg("Informational message")
   End Sub

   Private Sub Button2_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Button2.Click
      errorLogger.LogMsg("Error message")
   End Sub
End Class

Now, run the application (make sure that MessageLogTest is the startup application, which it should be if you created it first). Click each button one time. If you look at the output.txt file, it looks like this:

Informational message. 1
Error message. 1

You will notice that both objects created (infoLogger and errorLogger) successfully wrote to the text file. However, the static count of the number of messages shows both messages as number one. Why?

You have created two separate objects in memory. They are completely separate, so each object has its own LogMsg method, meaning that each has its own copy of the static iCount. Therefore, one message sent using the infoLogger gets the value of 1, but a message sent with errorLogger goes to the other object in memory, and also gets 1.

To avoid this situation, you could share the LogMsg method. This allows you to share the method across multiple instances of the object, meaning that all the objects will call through the same copy of the method.

To share the LogMsg function, return to the MessageLogger application and, in the Logger class, modify the definition of the function to look like this:

Public Shared Function LogMsg(ByVal psMessage As String)

By adding the keyword Shared, this method will now be shared across multiple instances of the object. To test this, delete the output.txt file. Now, run the application again, and press each button once. If you examine the output.txt again, you will see the following output has been produced:

Informational message. 1
Error message. 2

Now, you can see that regardless of which object you call, the count of the number of messages is incremented properly. This means that the same LogMsg method was called from two different objects because it has been shared between the two objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.188.95