views:

1883

answers:

1

Why won't XMLSerializer process my generic list?

Sub Main()
    Serializing()
End Sub

<System.Serializable()> _
Public Class User
    Public Sub New()
    End Sub

    Public Sub New(ByVal Username As String, ByVal UserId As Integer)
        Name = Username
        ID = UserId
    End Sub

    Public Name As String
    Public ID As Integer
End Class

Public Sub Serializing()
    Dim Users As New List(Of User)

    Dim u As New User
    u.Name = "bob"
    u.ID = 1
    Users.Add(u)

    u.Name = "bill"
    u.ID = 2
    Users.Add(u)

    u.Name = "ted"
    u.ID = 3
    Users.Add(u)

    Dim sw As New System.IO.StringWriter
    Dim ser As New System.Xml.Serialization.XmlSerializer(GetType(List(Of User)))
    ser.Serialize(sw, Users)

    Debug.WriteLine(sw.ToString)

End Sub

I get an exception on the "Dim ser" line, saying "Testing.Module1 is inaccessible due to its protection level. Only public types can be processed." ("Testing is the name of the application, and "Module1" is the name of the module; this is a console application).

+3  A: 

The problem is that you have included the class User inside of the Module Module1. The error message indicates the accessibility of this module is not public. Hence the actual accessibility of User is not public either since it is nested within the Module.

Change the definition of your outer Module to be Public or move the Class User outside the module and it should fix your problem.

EDIT

As several people pointed out, the cleanest way to achieve this is to put the User class into it's own file.

JaredPar
Yeap that it appears to be to me too. My preference would be to put the user Class in its own file.
RichardOD
I agree with Richard. Nested classes should typically be avoided, the rule of thumb is only nest and/or hide a class if there is 100% certainty that no other class should be aware of it. Since you're serializing the class it's clearly intended to be used elsewhere--so you really don't want it hidden
STW
Thanks for the feedback, all. This solved my problem.
DWRoelands