title: .NET XmlSerializer and nested classes in C#
body: <p>I have encountered some surprising behavior using XmlSerializer in C#.  Consider the following piece of code.</p>
  
  <pre><code>public class A : IEnumerable
  {
      public class B
      {
          [XmlAttribute]
          public string PropA { get; set; }
          [XmlElement]
          public string PropB { get; set; }
      }
  
      public IEnumerator GetEnumerator ()
      {
          yield break;
      }
  }
  
  class Program
  {
      static void Main (string[] args)
      {
          XmlSerializer serializer = new XmlSerializer(typeof(A.B));
  
          XmlTextWriter writer = new XmlTextWriter(@"E:\temp\test.xml", Encoding.Default);
          serializer.Serialize(writer, new A.B() { PropA = "one", PropB = "two" });
      }
  }
  </code></pre>
  
  <p>In this example I try to serialize an instance of nested class A.B, which itself doesn't make use of the container class A in any way.  But when I attempt to construct the XmlSerializer for it, the following exception is thrown:</p>
  
  <blockquote>
    <p>InvalidOperationException was unhandled:</p>
    
    <p>To be XML serializable, types which inherit from IEnumerable must have
    an implementation of Add(System.Object) at all levels of their
    inheritance hierarchy. Test.A does not implement Add(System.Object).</p>
  </blockquote>
  
  <p>XmlSerializer is trying to apply serialization constraints against type A when I'm actually trying to serialize type A.B.  My understanding however is that aside from privileged access to data in instances of the outer type, a nested type is not special and behaves as if it were in a namespace.  </p>
  
  <p>Is this understanding incorrect, and <strong>do the semantics of nested types or XmlSerializer justify this behavior, or does this feel like a bug in XmlSerializer?</strong></p>
  
  <p>In specific regard to XmlSerializer semantics, is there any documented requirement that enforces XmlSerializer constraints on all outer types when applied against a nested type?</p>