Serialize only changed properties of the object

1.8k Views Asked by At

In C# is it possible to serialize object with only the modified values?

For example: I have instance of the Button object bind into the PropertyGrid and I want to serialize that Button object with only the changed properties. In C# what was the best approach to archive this?

3

There are 3 best solutions below

0
On BEST ANSWER

You can iterate object's properties through reflection, compare it's properties with 'fresh' instance, and write down the difference somehow. But you should address many problems if you choose that path, like null handling, serializing non-serializable types, serializing references, etc. Here's just a sketch:

    public static string ChangedPropertiesToXml<T>(T changedObj)
    {
        XmlDocument doc=new XmlDocument();
        XmlNode typeNode = doc.CreateNode(XmlNodeType.Element, typeof (T).Name, "");
        doc.AppendChild(typeNode);
        T templateObj = Activator.CreateInstance<T>();
        foreach (PropertyInfo info in
            typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (info.CanRead && info.CanWrite)
            {
                object templateValue = info.GetValue(templateObj, null);
                object changedValue = info.GetValue(changedObj, null);
                if (templateValue != null && changedValue != null && !templateValue.Equals(changedValue))
                {
                    XmlElement elem =  doc.CreateElement(info.Name);
                    elem.InnerText = changedValue.ToString();
                    typeNode.AppendChild(elem);
                }
            }
        }
        StringWriter sw=new StringWriter();
        doc.WriteContentTo(new XmlTextWriter(sw));
        return sw.ToString();
    }

A call:

Button b = new Button();
b.Name = "ChangedName";
Console.WriteLine(SaveChangedProperties(b));

An output:

<Button>
   <Name>ChangedName</Name>
</Button>
0
On

Out of the blue, from the information you gave.

You first need to find the dirty properties in the object, you can have another project and track on that when ever there is a change in other properties. or isdirty property for each property or if you can compare with old object to new object.

Then in the ToString() method or you custom serialize method, override to generate the serialized object custom only with the changed properties.

It works for the POCO object, for complex button objects you make have to see how to do it.

its just and idea, more if there is code samples.

0
On

In your own types: yes, you can support this - via the ShouldSerialize* pattern, for example:

public string Name {get;set;}
public bool ShouldSerializeName() { return Name != null; }

However, on external types - it is entirely up to them whether they support this. Note that this will also tell the property-grid which to embolden.

In some cases, [DefaultValue({the default value})] will also work.