Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize only changed properties of the object

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?

like image 858
borncon2014 Avatar asked Nov 28 '25 11:11

borncon2014


2 Answers

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.

like image 105
Marc Gravell Avatar answered Dec 01 '25 02:12

Marc Gravell


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>
like image 34
cyberj0g Avatar answered Dec 01 '25 00:12

cyberj0g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!