punjabtechnicaluniversity.blogspot.in
Static/Shared classes are used when a class provides functionality which is not specific to any instance.In short if you want a object to be shared between multiple instances you will use a static/Shared class.
Following are features of Static/Shared classes :-
1. They can not be instantiated.By default a object is created on the first method call to that object.
2. Static/Shared classes can not be inherited.
3. Static/Shared classes can have only static members.
4. Static/Shared classes can have only static constructor.
Public Class ClsShared
Shared intCount As Integer
Public Function AddCount() As Integer
intCount = intCount + 1
Return intCount
End Function
End Class
Public Class FrmSharedClasses
Inherits System.Windows.Forms.Form
Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance1.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
End Sub
Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance2.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
End Sub
End Class
Static/Shared classes are used when a class provides functionality which is not specific to any instance.In short if you want a object to be shared between multiple instances you will use a static/Shared class.
Following are features of Static/Shared classes :-
1. They can not be instantiated.By default a object is created on the first method call to that object.
2. Static/Shared classes can not be inherited.
3. Static/Shared classes can have only static members.
4. Static/Shared classes can have only static constructor.
Note :- In CD there is a folder “WindowsShared” which has a sample code for shared variables.Below is a snippet.It has a “AddCount” function which increments a static “intCount” variable.In form there are two buttons which creates a new object and displays the count of the static variable.Even though the object is created and destroyed , the variable values does not change.It retains its old value.
Shared intCount As Integer
Public Function AddCount() As Integer
intCount = intCount + 1
Return intCount
End Function
End Class
Public Class FrmSharedClasses
Inherits System.Windows.Forms.Form
Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance1.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
End Sub
Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance2.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
End Sub
End Class
Shared/Static In Action
0 comments:
Post a Comment
North India Campus