brantonb
brantonb

Reputation: 709

Type is not serializable because it's not public?

I have a public class that won't serialize properly. When attempted, the following exception is thrown:

The data contract type 'MyProject.MyClass' is not serializable because it is not public. Making the type public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.

My class is public, though:

[DataContract]
public class MyClass
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    private int Count;

    public MyClass()
    {
        Name = string.Empty;
        Count = 0;
    }
}

Why am I getting this exception when the class is clearly public?

Upvotes: 5

Views: 3835

Answers (2)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59131

You might be able to fix this by writing custom serialization for this class. The built-in XML serialization can only serialize public properties.

You can do one of the following to work around this limitation:

  • Get rid of the DataMember attribute on Count
  • Make Count public
  • Implement IXmlSerializable (or whatever other serialization you need to), and serialize those private members manually

Upvotes: 2

brantonb
brantonb

Reputation: 709

In Windows Phone 7 apps, you can't serialize private members:

Well, it just so happens that WP7 apps run in a “partial trust” environment and outside of “full trust”-land, DataContractSerializer refuses to serialize or deserialize non-public members. Of course that exception was swallowed up internally by .NET so all I ever saw was that bizarre message about things that I knew for certain were public being “not public”. I changed all the private fields I was serializing to public and everything worked just fine. http://geekswithblogs.net/mikebmcl/archive/2010/12/29/datacontractserializer-type-is-not-serializable-because-it-is-not-public.aspx

Changing the code to avoid serializing private members fixes the issue.

Upvotes: 8

Related Questions