Search code examples
c#.netserializationsgen

Serialization of internal class to xml


I ran into problems when trying to xml serialize a class to xml after I changed it from public to internal. Before I changed protection level it was working fine, so I am looking for a way to get around the public only restriction.

The reason I want it to be internal is that I moved the class into a library and it's not useful outside the library.

A simple example of class layout:

[Serializable]
internal class InternalSerializable
{
    [XmlAttribute]
    public int Foo = 5;

    public InternalSerializable()
    {
    }
}

Normally XmlSerializer is automatically generated and have a random assembly name, so I tried using sgen.exe to pre-generate the XmlSerializer and reference it using:

[assembly: InternalsVisibleTo("FileFormats.XmlSerializers")]

but when running sgen with /verbose switch it says that only public types can be processed.

So I was wondering if anyone know how to trick sgen into processing internal types or otherwise serialize internal classes?

Edit: I got quite a few classes with this problem so I would prefer not to rewrite the whole thing


Solution

  • Hackish but you could make your class public and mark it with EditorBrowsable attribute to hide it from intellisense.

    [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    [Serializable]
    public class InternalSerializable
    

    In C#, EditorBrowsable work only on compiled assemblies : Hiding GetHashCode/Equals/ToString from fluent interface classes intellisense in Visual Studio for C#?