Mike Cialowicz
Mike Cialowicz

Reputation: 10020

Can't call Serialize() on instance of serializable singleton class in VB.NET

I have a VB.NET singleton class which implements Serializable:

Imports System.IO
Imports System.Runtime.Serialization

<Serializable()> Public Class CoordinateHistory
    Private Shared _thisInstance As CoordinateHistory

    Private gpsHistory As Dictionary(Of DateTime, GpsTimeCoordinate)
    Private gpsTimes As List(Of DateTime)

    Public Event NewStatusInformation(statusInfo As String)

    Protected Sub New()
        gpsHistory = New Dictionary(Of DateTime, GpsTimeCoordinate)
        gpsTimes = New List(Of DateTime)
    End Sub

    Public Shared Function getInstance() As CoordinateHistory
        If _thisInstance Is Nothing Then
            _thisInstance = New CoordinateHistory
        End If

        Return _thisInstance
    End Function

    Public Function getHistoryCount() As Integer
        Return gpsHistory.Count
    End Function

    ' bunch of other class functions below...
End Class

My problem is that I can't actually call .Serialize() on the instance of this class, like all of the examples online show. What am I doing wrong? Thanks!

Upvotes: 3

Views: 515

Answers (2)

Dave M
Dave M

Reputation: 1322

The issue could be your classes public event. There is an article here that describes the issues of serializing VB.NET classes with events and how to work around them.

Edit: See also this possibly related question.

Upvotes: 2

competent_tech
competent_tech

Reputation: 44931

I believe the issue is your Protected Sub. If you change it to Public, you may be able to Serialize correctly.

Update

I didn't have any issues serializing the default instance using a BinaryFormatter:

Dim abData As Byte()

Using oStream As New MemoryStream
    Call (New BinaryFormatter).Serialize(oStream, CoordinateHistory.getInstance())

    abData = oStream.ToArray()
End Using

or an XMLFormatter:

Dim sData As String

Using oStream As New MemoryStream
    Dim oSerializer As New XmlSerializer(CoordinateHistory.getInstance().GetType)

    oSerializer.Serialize(oStream, CoordinateHistory.getInstance())

    sData = Encoding.Default.GetString(oStream.ToArray())
End Using

Perhaps it is the serialization framework you are using?

Upvotes: 3

Related Questions