<p>Using C# .NET 2.0, I have a composite data class that does have the <code>[Serializable]</code> attribute on it.  I am creating an <code>XMLSerializer</code> class and passing that into the constructor:</p>

<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
</code></pre>

<p>I am getting an exception saying: </p>

<blockquote>
  <p>There was an error reflecting type.</p>
</blockquote>

<p>Inside the data class there is another composite object.  Does this also need to have the <code>[Serializable]</code> attribute, or by having it on the top object, does it recursively apply it to all objects inside?</p>

[{'answer_id': 60581, 'author': 'Lamar', 'author_id': 3566, 'author_profile': 'https://Stackoverflow.com/users/3566', 'pm_score': 10, 'selected': True, 'text': '<p>Look at the inner exception that you are getting.  It will tell you which field/property it is having trouble serializing.  </p>\n\n<p>You can exclude fields/properties from xml serialization by decorating them with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute" rel="noreferrer"><code>[XmlIgnore]</code></a> attribute.  </p>\n\n<p><code>XmlSerializer</code> does not use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute" rel="noreferrer"><code>[Serializable]</code></a> attribute, so I doubt that is the problem.</p>\n'}, {'answer_id': 60583, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 0, 'selected': False, 'text': '<p>Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.</p>\n'}, {'answer_id': 60596, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 3, 'selected': False, 'text': '<p>All the objects in the serialization graph have to be serializable.</p>\n\n<p>Since <code>XMLSerializer</code> is a blackbox, check these links if you want to debug further into the serialization process..</p>\n\n<p><a href="http://www.hanselman.com/blog/CategoryView.aspx?category=XmlSerializer" rel="nofollow noreferrer">Changing where XmlSerializer Outputs Temporary Assemblies</a> </p>\n\n<p><a href="http://www.hanselman.com/blog/HOWTODebugIntoANETXmlSerializerGeneratedAssembly.aspx" rel="nofollow noreferrer">HOW TO: Debug into a .NET XmlSerializer Generated Assembly</a> </p>\n'}, {'answer_id': 60610, 'author': 'Darren', 'author_id': 6065, 'author_profile': 'https://Stackoverflow.com/users/6065', 'pm_score': 2, 'selected': False, 'text': '<p>I too thought that the Serializable attribute had to be on the object but unless I\'m being a complete noob (I am in the middle of a late night coding session) the following works from the <a href="http://www.sliver.com/dotnet/SnippetCompiler/" rel="nofollow noreferrer">SnippetCompiler</a>:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Xml;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\n\npublic class Inner\n{\n    private string _AnotherStringProperty;\n    public string AnotherStringProperty \n    { \n      get { return _AnotherStringProperty; } \n      set { _AnotherStringProperty = value; } \n    }\n}\n\npublic class DataClass\n{\n    private string _StringProperty;\n    public string StringProperty \n    { \n       get { return _StringProperty; } \n       set{ _StringProperty = value; } \n    }\n\n    private Inner _InnerObject;\n    public Inner InnerObject \n    { \n       get { return _InnerObject; } \n       set { _InnerObject = value; } \n    }\n}\n\npublic class MyClass\n{\n\n    public static void Main()\n    {\n        try\n        {\n            XmlSerializer serializer = new XmlSerializer(typeof(DataClass));\n            TextWriter writer = new StreamWriter(@"c:\\tmp\\dataClass.xml");\n            DataClass clazz = new DataClass();\n            Inner inner = new Inner();\n            inner.AnotherStringProperty = "Foo2";\n            clazz.InnerObject = inner;\n            clazz.StringProperty = "foo";\n            serializer.Serialize(writer, clazz);\n        }\n        finally\n        {\n            Console.Write("Press any key to continue...");\n            Console.ReadKey();\n        }\n    }\n\n}\n</code></pre>\n\n<p>I would imagine that the XmlSerializer is using reflection over the public properties.</p>\n'}, {'answer_id': 60665, 'author': 'Jeremy McGee', 'author_id': 3546, 'author_profile': 'https://Stackoverflow.com/users/3546', 'pm_score': 7, 'selected': False, 'text': "<p>Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.</p>\n"}, {'answer_id': 60714, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 3, 'selected': False, 'text': '<p>Also be aware that <code>XmlSerializer</code> cannot serialize abstract properties.. See my question <a href="https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types">here</a> (which I have added the solution code to)..</p>\n\n<p><a href="https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types">XML Serialization and Inherited Types</a></p>\n'}, {'answer_id': 72043, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I have been using the <code>NetDataSerialiser</code> class to serialise \nmy domain classes. <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx" rel="nofollow noreferrer">NetDataContractSerializer Class</a>.</p>\n\n<p>The domain classes are shared between client and server.</p>\n'}, {'answer_id': 1076259, 'author': 'Charlie Salts', 'author_id': 37971, 'author_profile': 'https://Stackoverflow.com/users/37971', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.  </p>\n\n<p>I found a work around <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx" rel="nofollow noreferrer">here</a>. </p>\n'}, {'answer_id': 2715915, 'author': 'Luca', 'author_id': 161554, 'author_profile': 'https://Stackoverflow.com/users/161554', 'pm_score': 3, 'selected': False, 'text': '<p>If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the <a href="http://msdn.microsoft.com/it-it/library/system.xml.serialization.ixmlserializable%28VS.80%29.aspx" rel="nofollow noreferrer">IXmlSerialiable</a> interface, which will allow you more freedom <em>at the cost of more verbose coding</em>.</p>\n\n<pre><code>public class NetService : IXmlSerializable\n{\n    #region Data\n\n        public string Identifier = String.Empty;\n\n        public string Name = String.Empty;\n\n        public IPAddress Address = IPAddress.None;\n        public int Port = 7777;\n\n    #endregion\n\n    #region IXmlSerializable Implementation\n\n        public XmlSchema GetSchema() { return (null); }\n\n        public void ReadXml(XmlReader reader)\n        {\n            // Attributes\n            Identifier = reader[XML_IDENTIFIER];\n            if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)\n            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);\n            if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)\n            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);\n        }\n\n        public void WriteXml(XmlWriter writer)\n        {\n            // Attributes\n            writer.WriteAttributeString(XML_IDENTIFIER, Identifier);\n            writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());\n            writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());\n        }\n\n        private const string XML_IDENTIFIER = "Id";\n\n        private const string XML_NETWORK_ADDR = "Address";\n\n        private const string XML_NETWORK_PORT = "Port";\n\n    #endregion\n}\n</code></pre>\n\n<p>There is an interesting <a href="http://msdn.microsoft.com/en-us/magazine/cc164135.aspx" rel="nofollow noreferrer">article</a>, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.</p>\n\n<hr>\n\n<p>The article say:</p>\n\n<blockquote>\n  <p>IXmlSerializable is covered in the official documentation, but the documentation states it\'s not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you\'re willing to accept this uncertainty and deal with possible changes in the future, there\'s no reason whatsoever you can\'t take advantage of it.</p>\n</blockquote>\n\n<p>Because this, I suggest to implement you\'re own <code>IXmlSerializable</code> classes, in order to avoid too much complicated implementations.</p>\n\n<p>...it could be straightforward to implements our custom <code>XmlSerializer</code> class using reflection.</p>\n'}, {'answer_id': 4471269, 'author': 'LepardUK', 'author_id': 44247, 'author_profile': 'https://Stackoverflow.com/users/44247', 'pm_score': 2, 'selected': False, 'text': '<p>I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.</p>\n\n<pre><code>    [System.Xml.Serialization.XmlElementAttribute(Order = XX)]\n</code></pre>\n\n<p>I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.</p>\n'}, {'answer_id': 7450751, 'author': 'Dennis Calla', 'author_id': 510199, 'author_profile': 'https://Stackoverflow.com/users/510199', 'pm_score': 5, 'selected': False, 'text': '<p>I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other).  The inner exception looked like this: </p>\n\n<p>\'Types BaseNamespace.Class1\' and \'BaseNamespace.SubNamespace.Class1\' both use the XML type name, \'Class1\', from namespace \'\'. Use XML attributes to specify a unique XML name and/or namespace for the type. </p>\n\n<p>Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.  </p>\n\n<p>What I needed to do was add an attribute to one of the classes (I added to the base class):</p>\n\n<pre><code>[XmlType("BaseNamespace.Class1")]\n</code></pre>\n\n<p>Note: If you have more layers of classes you need to add an attribute to them as well.</p>\n'}, {'answer_id': 8835456, 'author': 'jkokorian', 'author_id': 1068959, 'author_profile': 'https://Stackoverflow.com/users/1068959', 'pm_score': 3, 'selected': False, 'text': '<p>I just got the same error and discovered that a property of type <code>IEnumerable&lt;SomeClass&gt;</code> was the problem. It appears that <code>IEnumerable</code> cannot be serialized directly.</p>\n\n<p>Instead, one could use <code>List&lt;SomeClass&gt;</code>.</p>\n'}, {'answer_id': 13923224, 'author': 'Jeremy Brown', 'author_id': 1911312, 'author_profile': 'https://Stackoverflow.com/users/1911312', 'pm_score': 1, 'selected': False, 'text': '<p>I had a situation where the Order was the same for two elements in a row</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]\n</code></pre>\n\n<p>.... some code ...</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]\n</code></pre>\n\n<p>When I changed the code to increment the order by one for each new Property in the class, the error went away.</p>\n'}, {'answer_id': 21954336, 'author': 'Stefan Michev', 'author_id': 754571, 'author_profile': 'https://Stackoverflow.com/users/754571', 'pm_score': 3, 'selected': False, 'text': '<p>Most common reasons by me:</p>\n\n<pre><code> - the object being serialized has no parameterless constructor\n - the object contains Dictionary\n - the object has some public Interface members\n</code></pre>\n'}, {'answer_id': 42273101, 'author': 'Kiran.Bakwad', 'author_id': 2940450, 'author_profile': 'https://Stackoverflow.com/users/2940450', 'pm_score': 0, 'selected': False, 'text': '<pre><code>[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>[XmlIgnore]\nstring [] strFielsName {get;set;}\n</code></pre>\n'}, {'answer_id': 44192135, 'author': 'Curious Dev', 'author_id': 3952153, 'author_profile': 'https://Stackoverflow.com/users/3952153', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable. </p>\n'}, {'answer_id': 59372719, 'author': 'chxzy', 'author_id': 4871263, 'author_profile': 'https://Stackoverflow.com/users/4871263', 'pm_score': 0, 'selected': False, 'text': '<p>I have a slightly different solution to all described here so far, so for any future civilisation here\'s mine!</p>\n\n<p>I had declared a datatype of "time" as the original type was a <code>TimeSpan</code> and subsequently changed to a <code>String</code>:</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]\n</code></pre>\n\n<p>however the actual type was a string</p>\n\n<pre><code>public string TimeProperty {\n    get {\n        return this.timePropertyField;\n    }\n    set {\n        this.timePropertyField = value;\n        this.RaisePropertyChanged("TimeProperty");\n    }\n}\n</code></pre>\n\n<p>by removing the <code>DateType</code> property the <code>Xml</code> can be serialized</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(Order=3)]\npublic string TimeProperty {\n    get {\n        return this.timePropertyField;\n    }\n    set {\n        this.timePropertyField = value;\n        this.RaisePropertyChanged("TimeProperty");\n    }\n}\n</code></pre>\n'}, {'answer_id': 59372769, 'author': 'Iqra.', 'author_id': 7596696, 'author_profile': 'https://Stackoverflow.com/users/7596696', 'pm_score': 1, 'selected': False, 'text': "<p>I was getting the same error when I created a property having a datatype - <code>Type</code>. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was <code>Type</code>) in my case. The solution is as follows: </p>\n\n<pre><code>    [XmlIgnore]\n    public Type Type { get; set; }\n</code></pre>\n"}, {'answer_id': 66289667, 'author': 'Esperento57', 'author_id': 3735690, 'author_profile': 'https://Stackoverflow.com/users/3735690', 'pm_score': 2, 'selected': False, 'text': '<p>Sometime, this type of error is because you dont have constructur of class without argument</p>\n'}]
['https://Stackoverflow.com/questions/60573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653/']