Search code examples
c#serializationconfigurationnetdatacontractserializer

How to serialize type derived from ConfigurationSection with NetDataContractSerializer


I wrote my type derived from ConfigurationSection tagged all properties with DataMember and class with DataContract, however program crashes stating I cannot inherit my type from a type that is not marked with DataContract.

So how could I use this serializer with ConfigurationSection?

[DataContract]
public sealed class MyConfig : ConfigurationSection
{
    [DataMember]
    [ConfigurationProperty("ConnectionTimeout", DefaultValue = 1000)]
    public int ConnectionTimeout
    {
        get { return (int)this["ConnectionTimeout"]; }
        set { this["ConnectionTimeout"] = value; }
    }
    ... // other values
}

Solution

  • There is another way -- instead of relying on automatic serialization, write your custom serialization manually. Since NetDataContractSerializer supports it, you can end up with just single type with 2 additional methods (more precisely: extra method for serializing and constructor for deserializing).

    As for example see the post: When using ISerializable with DataContractSerializer, how do I stop the serializer from outputting type information?