Can WCF keep reference equality over the wire?
c#, reference, wcf
Solution
You have to explicitly tell WCF to preserve references by specifying
[DataContract(IsReference = true)]
otherwise reference equality is lost during message construction.
Problem
Say you have a few classes defined as ``` [DataContract] public class Foo { [DataMember] public List<Bar> Bars {get; set;} } [DataContract] public class Bar { [DataMember] public string Baz { get; set; } } public class Service1 : IService1 { public bool Send(Foo foo) { var bars = foo.Bars; bars[0].Baz = "test2"; return bars[0].Baz == bars[1].Baz; } } [ServiceContract] public interface IService1 { [OperationContract] bool Send(Foo composite); } ``` Assuming I am using WCF to WCF with a shared data contract DLL between the client and server, if I do something like the following ``` static void Main(string[] args) { using (var client = new ServiceReference.Service1Client()) { var bar = new Bar(); bar.Baz = "Start"; List<Bar> bars = new List<Bar>(); bars.Add(bar); bars.Add(bar); var foo = new Foo(); foo.Bars = bars; Console.WriteLine(bars[0].Baz == bars[1].Baz); bars[0].Baz = "test1"; Console.WriteLine(bars[0].Baz == bars[1].Baz); Console.WriteLine(client.Send(foo)); Console.ReadLine(); } } ``` I get `True`, `True`, `False` as my result which means that `bars[0]` and `bars[1]` did not point to the same object on the server. Am I doing something wrong, or is it impossible to have shared references over WCF?