Serializing a generic collection with XMLSerializer in VB.NET

generics, vb.net, xml-serialization

Solution

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.

Problem

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).

Original source