Ksdmg Ksdmg - 1 month ago 7
Vb.net Question

Can I shorten the access of my Lazy class without disadvantage

So this is how I would design my Lazy class (From this SO):

Public NotInheritable Class MySingleton
Private Shared ReadOnly _instance As New Lazy(Of MySingleton)(Function() New _
MySingleton(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance() As MySingleton
Get
Return _instance.Value
End Get
End Property

Private _MyString As String
Public Property MyString As String
Get
Return _MyString
End Get
Set(value As String)
_MyString = value
End Set
End Property

End Class


To access the _MyString value, I do the following:

Dim MyString = MySingleton.Instance.MyString


In fact, I always have to type the ".Instance."
Does it have any disadvantage if I design the Property the following way:

Public Property MyString As String
Get
Return instance._MyString
End Get
Set(value As String)
instance._MyString = value
End Set
End Property


So I can access it without always writing the ".Instance."

Dim MyString = MySingleton.MyString

Answer

Yes you can (of course with Public Shared Property), but you are losing some of the benefits from singleton over static classes.

Lets say you have another class MyWorker

Public Class MyWorker

    Public Sub Work(instance as MySingleton)
       Dim value as String = instance.MyString
       ' Do something ...
    End Sub

End Class

I would not do this. This may not look like a big issue, but on the long run you have a tight coupling in your code base and a hard time mocking your class for unit testing, one of the reasons for using singeltons over static classes in the first place.

I often use this approach, when accessing Singelton values mutiple times:

Dim instance as MySingelton = MySingelton.Value
If instance.MyString = "something" Then
    instance.MyString = "something else"
End If

much cleaner approach.