For example
[DataContract]
public abstract class BaseClass
{
public abstract string id { get; set; }
}
[DataContract(Name = "class1")]
public class concreteClass1 : BaseClass
{
public concreteClass1() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
[DataContract(Name = "class2")]
public class concreteClass2 : BaseClass
{
public concreteClass2() { }
[DataMember]
public override string id { get; set; }
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
}
When I try to serialize a dictionary containing one of the concrete classes like this
static public void Main(string[] args){
Dictionary<string, BaseClass> items = new Dictionary<string, BaseClass>();
items.Add("1", new concreteClass1() { id = "1", prop1 = "blah1" });
items.Add("11", new concreteClass1() { id = "11", prop1 = "blah11" });
var serializer = new DataContractSerializer(items.GetType());
string xmlString = string.Empty;
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = System.Xml.Formatting.Indented;
serializer.WriteObject(writer, items );
writer.Flush();
xmlString = sw.ToString();
}
}
}
I get this error when trying to WriteObject
Type 'ConsoleTest.Program+Base' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
Is there a way to solve this?
EDIT: I also tried using KnownType on the base class but it didn't work
[DataContract]
[KnownType(typeof(concreteClass1))]
[KnownType(typeof(concreteClass2))]
public abstract class BaseClass
{
public abstract string id { get; set; }
}