Scott Hanselman

You must implement the Add(System.Object) method on MyClass because it inherits from IEnumerable

August 24, 2005 Comment on this post [3] Posted in ASP.NET | Learning .NET | XmlSerializer | Africa
Sponsored By

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.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
August 24, 2005 11:42
This is one of the reasons why I create a library of Messages, and do not try to use XML Serialization on business objects. . Yes, at first it seems like more work, but in the end you will understand that the message may look a lot like the business object, but they accomplish very different goals.
August 26, 2005 21:57
Sounds like they need to create IAddable[T] { Add(T item); }. ;)

By the way, that no-html-allowed bit gets in the way of typing in generics. Could dasBlog merely output using HTML encoding, instead?
September 15, 2005 9:01
No HTML maybe to avoid SPAM, but really inconvient to some visitor.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.