This project has moved. For the latest updates, please go here.


Property marked new in subclass does not get serialized


Properties in subclasses are ignored if there is a property with the same name in the base class.

Modifed the ChildDataContractTest sligtly (from line 4408):
    public class BaseDataContract
      [DataMember(Name = "virtualMember")]
      public virtual string VirtualMember { get; set; }

      [DataMember(Name = "nonVirtualMember")]
      public string NonVirtualMember { get; set; }

      public virtual object NewMember { get; set; }

    public class ChildDataContract : BaseDataContract
      [DataMember(Name = "NewMember")]
      public virtual new string NewMember { get; set; }
      public override string VirtualMember { get; set; }
      public string AddedMember { get; set; }

    public void ChildDataContractTest()
      var cc = new ChildDataContract
          VirtualMember = "VirtualMember!",
          NonVirtualMember = "NonVirtualMember!",
          NewMember = "NewMember!"

      string result = JsonConvert.SerializeObject(cc);
      Assert.AreEqual(@"{""NewMember"":""NewMember!"",""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
The property is filtered away in ReflectionUtils.GetFieldsAndProperties. If this method just returns all properties this works, but I guess this can have side effects? I did this change and all tests run fine.

I came across this when serializing a model which we us in WCF. The base type has a property of type object (which can not be serialized by WCF), while the subclass overrides this with an actual type and is marked with the DataMember attribute.
Closed Apr 6, 2013 at 3:59 PM by JamesNK