You must implement the Add(System.Object) method on MyClass because it inherits from IEnumerable
Peter was getting the error "You must implement the Add(System.Object) method on MyClass because it inherits from IEnumerable" while serializing an object. He added an Add() method and the error went away, but he was rightfully confused by this odd message because IEnumerable doesn't require an Add as part of its contract! The error message arguably uses the word "implement" in a way that implies something about the interface in question.
Remember that the XmlSerializer has to serialize and deserialize, and does so only via public means. For something that implements IEnumerable, there'd be no way to get objects back in without something like an Add.
Sairama pointed to this paragraph buried in the MSDN docs:
The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. For classes implementing ICollection, values to be serialized will be retrieved from the indexed Item property, not by calling GetEnumerator
Now playing: Ladysmith Black Mambazo - N'kosi Sikeleli Afrika (God Bless Africa)
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
By the way, that no-html-allowed bit gets in the way of typing in generics. Could dasBlog merely output using HTML encoding, instead?
Comments are closed.