Can you improve upon this generic?
I'm trying to reduce code bloat, reduce errors and simplify codebehind by use of generics. In this case I'm applying generics to declaration of persistable properties. Persistance is implemented by My.Settings. Here's the code so far.
' must be defined in same project as My.Settings!
Public Class MySettingsProperty(Of T)
Implements System.ComponentModel.INotifyPropertyChanged
Private m_Name As String
Sub New(ByVal Name As String)
m_Name = Name
End Sub
Sub New(ByVal Name As String, ByVal InitialValue As T)
m_Name = Name
Value = InitialValue
End Sub
Public Property Value As T
Get
Return CType(My.Settings(m_Name), T)
End Get
Set(ByVal value As T)
My.Settings(m_Name) = value
RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Value"))
End Set
End Property
Private Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
Usage:
Public Property Host As New MySettingsProperty(Of String)("Host")
Host.Value = "127.0.0.1"
Debug.WriteLine(Host.Value)
Advantages:
Disadvantages
I just ported this from c#
to vb
so hopefully it's suitable:
Module SettingsHelper
Public Function GetSetting(Of TSetting)(ByVal selector As Func(Of My.MySettings, TSetting)) As TSetting
Return selector(My.Settings)
End Function
Public Sub SetSetting(ByVal action As Action(Of My.MySettings))
action(My.Settings)
End Sub
End Module
And usage:
Debug.WriteLine(SettingsHelper.GetSetting(Function(s) s.Setting1))
SettingsHelper.SetSetting(Sub(s) s.Setting1 = "new value")
Hope this helps.