Question

I have one class with a private static (shared, since I'm in VB.BET) field and its associated public static property, since it stores one variable that should be the same to all the instances of this class.

My Class looks like this:

Public MustInherit Class NitrogenController
    Private _active As Boolean
    Private Shared _controlInterval As TimeSpan
    Private _lastControlTime As Date

    Public Property Active() As Boolean
    Public Shared Property ControlInterval() As System.TimeSpan

    'other properies that must be persisted

    Public Function Control() As Boolean
        If Not Now > _lastControlTime.Add(_controlInterval) Or Not _active Then
            Return False
        Else
            DoControl()
            _lastControlTime = Now
            Return True
        End If
    End Function
End Class

The problem arrives when trying to binary serialize these kind of objects, since this shared field is nos being properly stored and returns to its default value when deserializing.

I suppose this is the expected behaviour, so my question is... how can I make a shared field persistent? I have read some comments to similar questions that say that this is a bad design, but it really makes sense (AFAIK) in my case, since this variable should be the same to all the object, but can be changed by the user and therefore should be stored.

Can you suggest another way of doing it?

Thanks!

Was it helpful?

Solution

What you have read, in my opinion, is correct. This is, likely, a bad design. However, if you must, there are two ways to do this with the XmlSerializer. The easy way would be to simply add a public instance (non-shared) property which has a getter and setter which simply wrap the shared property, for instance:

Public MustInherit Class NitrogenController
    Public Shared Property ControlInterval As TimeSpan

    Public Property CurrentControlInterval() As TimeSpan
        Get
            Return ControlInterval 
        End Get
        Set(value As TimeSpan)
            ControlInterval = value
        End Set        
    End Property
End Class

If you aren't satisfied with that method, the second, more involved, option would be to override the default serialization logic by implementing the ISerializable interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top