Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property: Get: Set: Serialize to XML

I have a class defined that auto increments a property in its get method. I am trying to serialize this object to an XML and the auto-incremented property is not being printed. Any help is appreciated.

public class Program
{
    public static void Main()
    {   
        
        MyClass _myClass = new MyClass();
        string transactionXML = string.Empty;
        Console.WriteLine("Current ID: " + _myClass.ID);
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
                System.IO.StringWriter _sw = new System.IO.StringWriter();
                System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(_sw);
                xmlSerializer.Serialize(writer, _myClass);
                transactionXML = _sw.ToString();
        Console.WriteLine("XML:\n" + transactionXML);
    }
    
     [Serializable]
    public class MyClass
    {
        long last_id = 0;
        public string ID{get { return System.Threading.Interlocked.Increment(ref last_id ).ToString("D6"); }}

    }
}

When I try to run this, it runs with no errors, but does not print the ID in the XML.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you need to extend you "MyClass" ID with a setter like this:

[Serializable]
public class MyClass
{
    long last_id = 0;
    public string ID { get { return System.Threading.Interlocked.Increment(ref last_id).ToString("D6"); } set { } }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading