WCF DataContracts

I have a WCF service for internal clients - we have control over all clients. Therefore, we will use the data contract library to deny the need for proxy generation. I would like to use some readonly properties and have some datacontracts without default constructors. Thanks for your help...

+12
wcf datacontract
Oct 05 '08 at 21:20
source share
1 answer

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); } } 
+24
Oct 05 '08 at 21:31
source share



All Articles