I almost know where your bug is, but, unfortunately, you did not show your code sample with that bug. Let's do the following: I'll show you a completely working code sample, so you can compare what's missing.
But I know from experience that the most typical bug here is an incorrect enum
definition: missing or incorrect DataContract
attribute, missing [EnumMember]
attribute, or both. For some reason, you did not show it. Ah, yes, I can see from your exception information that [EnumMember]
is missing. Okay, that explains your problem.
Would you like to check it? Please see:
namespace DataContracts {
using System.Runtime.Serialization;
using FileStream = System.IO.FileStream;
using FileMode = System.IO.FileMode;
static class DefinitionSet {
internal const string dataContractNamespace = "https/www.my.site.org/contracts/demo";
internal const string filename = "demo.xml";
} //DefinitionSet
[DataContract(Namespace = DefinitionSet.dataContractNamespace)]
enum ConditionType {
[EnumMember] Excellent, [EnumMember] Good,
[EnumMember] Fair, [EnumMember] Bad,
[EnumMember] StackOverflowQuestion, }
[DataContract(Namespace = DefinitionSet.dataContractNamespace)]
class Demo {
[DataMember] // doesn't have to be public
public ConditionType Type { get; set; }
}
static class DataContractDemo {
static void TestSerialization() {
DataContractSerializer dcs = new(typeof(Demo));
dcs.WriteObject(new FileStream(
DefinitionSet.filename,
FileMode.Create),
new Demo());
} //TestSerialization
static void Main() {
TestSerialization();
} //Main
} //class DataContractDemo
}
So, make sure you fix your enum
definition. It should fix your problem unless you have bugs in other Data Contract types or member definitions. Please let us know if it fixes your problem and accept the answer unless you have other problems or further question.