I have a class that implements ICollection for convenience. When the class gets serialized to XML all the public properties are skipped and only the actual collection gets serialized. I read the following from the MSDN
Classes that implement ICollection or IEnumerable.
- Only collections are serialized, not public properties.
Is there anyway to work around this? Is there a way to have a class that implements ICollection and still will output the public properties? Or do I have to use an XmlWriter and do it myself?
Just in case an example is needed.
public class Batch: ICollection<Foo>
{
public string Bar { get; set; }
public int Baz { get; set; }
public List<Foo> Foos { get; private set; }
public IEnumerator<Foo> GetEnumerator()
{
return Foos.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Foos.GetEnumerator();
}
public void Add(Foo item)
{
Foos.Add(item);
}
public void Clear()
{
Foos.Clear();
}
public bool Contains(Foo item)
{
return Foos.Contains(item);
}
public void CopyTo(Foo[] array, int arrayIndex)
{
Foos.CopyTo(array, arrayIndex);
}
public bool Remove(Foo item)
{
return Foos.Remove(item);
}
public int Count { get { return Foos.Count; } }
public bool IsReadOnly { get { return false; } }
}
The reason it is this way is that in another part of my code I am dealing with collections of things. IList IList etc. But for the batch there is information that applies to every Foo but that information is the same for every foo for one particular batch. Like perhaps a batch ID or Created DateTime. I wanted to be able to treat my batch and my other collections in the same way in some parts of my code because all i care about that is a collection and has a count. I don't care that some information is identical to every item in that collection.
The reason I wanted to do that was for serialization. I was trying to remove redundant information. If there is another way to structure my class that I do not lose that very important count then I am all ears. I was hoping to avoid creating another interface that just contains a count for a simple thing like this. It felt dirty but it might be the right thing.