Readonly properties are fine as long as you mark the (non-readonly) field as [DataMember], and not the property. Unlike the XmlSerializer, IIRC DataContractSerializer does not use ctor by default - it uses a separate reflection mechanism to create uninitialized instances. Except for the mono " Olive " (WCF port), where it uses the default ctor value (at the moment or at some point in the recent past).
Example:
using System; using System.IO; using System.Runtime.Serialization; [DataContract] class Foo { [DataMember(Name="Bar")] private string bar; public string Bar { get { return bar; } } public Foo(string bar) { this.bar = bar; } } static class Program { static void Main() { DataContractSerializer dcs = new DataContractSerializer(typeof(Foo)); MemoryStream ms = new MemoryStream(); Foo orig = new Foo("abc"); dcs.WriteObject(ms, orig); ms.Position = 0; Foo clone = (Foo)dcs.ReadObject(ms); Console.WriteLine(clone.Bar); } }
Marc Gravell Oct 05 '08 at 21:31 2008-10-05 21:31
source share